ActionScript, Java → When instanceof doesn’t recognize an instanceof.
Java’s ‘instanceof’ keyword is not the same as ActionScript’s ‘is’ keyword. In theory, they do the same thing: find out if an instance of an object implements a class or interface. In reality, they’re quite different.
Java compares for an exact match. ActionScript compares for a match or any subclass of the class being compared.
Let’s say we have class A which implements interface I. And we have class B which is a subclass of A (and implicitly implements interface I).
Java:
if( A instanceof I ) // True
print( "yeah" );
if( B instanceof A ) // True
print( "yeah" );
if( B instanceof I ) // False!
print( "yeah" );
ActionScript:
if( A is I ) // True
print( "yeah" );
if( B is A ) // True
print( "yeah" );
if( B is I ) // True!
print( "yeah" );
So, having learned a lot of ActionScript before diving into Java, I expected ‘instanceof’ to behave just like ‘is’. But no. And that was annoying not to realize at first. So, you’ve been warned!!
Update: Hmm, now I wonder if overloading method parameters behaves the same way as instanceof in Java? I’m going to be safe and make an interface for any classes that have multiple subclasses (ie, categories of entities which require special behaviors). It’s still polymorphic, so I guess it’s “good design.” I haven’t had quite enough experience digging into the reasons for Java’s language design choices.
Update 2: Of course I had to test the behavior of overloaded methods. Turns out that Java isn’t as exacting with overloaded methods–which is a relief!
For example, I have an Entity class, and a subclass called ItemEntity. I need to do some special handling on an ItemEntity (or any subclass of it) in a method that takes Entity as a parameter. Overloading that method to take an ItemEntity gives me the desired behavior for ItemEntity or any subclass of ItemEntity. Yay!
My first approach was to get around it entirely by encoding all values that require more than 1 byte into hex strings. What a joyful aside that was! (Sarcasm, you see.) I mean, now I know how to encode anything to hex and back and do it sideways, too. But, this wasn’t working so well and it was bloating the nice binary format anyway. (No, I wasn’t really concerned about the size of the packets based on that, but if there’s a better way and it’s more space efficient–why not?)