Disclaimer: This is very basic Java stuff. Anyone who has programmed in Java for a couple of months will know this and can safely skip this entry.

Take the two classes below:

public class SuperFoo {
}
public class Foo extends SuperFoo {
}
Q:What will the below print?

public static void main(String[] args) {
SuperFoo superFoo = new SuperFoo();
Foo foo = new Foo();

if (superFoo instanceof Foo) {
System.out.println(“superFoo instanceof Foo”);
}

if (foo instanceof SuperFoo) {
System.out.println(“foo instanceof SuperFoo”);
}
}

A: foo instanceof SuperFoo.

An instance of Foo can do whatever an instance of SuperFoo does as Foo is a subclass of SuperFoo. superFoo is not an instance of Foo as an object of type SuperFoo cannot do whatever an object of type Foo does because foo is subclass of SuperFoo and can have some additional methods not present in SuperFoo.

Q: Will the below work?

if (foo instanceof Integer) {
}
A: No. To use instanceof the classes have to be in the same hierarchy. Here there is no relation between Foo and Integer class. So you cannot use instanceof. Compiler will flag an error.

Q: What about usage with interfaces? Will the below work?

if (foo instanceof Collection) {
System.out.println(“foo instanceof Collection”);
}
A: This is not a compiler error but will resolve to false as foo does not implement Collection.

Now consider the interesting scenario below:

SuperFoo superFoo = new Foo();

if (superFoo instanceof Foo) {
System.out.println(“superFoo instanceof Foo”);
}

if (superFoo instanceof SuperFoo) {
System.out.println(“superFoo instanceof SuperFoo”);
}

This will print both superFoo instanceof Foo and superFoo instanceof SuperFoo. From this we can clearly make out that it’s not the compile time type that matters but the actual object i.e the type resolution is done at runtime and not at compile time.

Finally the below will always be false

if (null instanceof Foo) {
}

Advertisements