Tuesday, September 7, 2010

Difference between instanceof operator and isAssignableFrom method - Explained once more

In this article I tried to re-explain the aged question of comparing instanceof operator with isAssignableFrom() method available in Class class. Note that the scope of this blog doesn’t include syntactical and performance related comparison but I tried to explain the core and subtle difference between these 2 options (which are typically used to verify correct type conversion).
The instanceof operator ensures that the left operand is an instance of the right operand or a subclass of it. On the other hand Class.isAssignableFrom() method, as the name suggests, indicates whether an instance of the class, passed as parameter to this method, can be assigned to the reference variable of type indicated by the class on which this method is called. Thus the statement

x instanceof Y

checks if the object referred by x variable is an instance of Y or a subclass of Y. While the statement


checks if an instance of Y class can be assigned to the reference variable of type indicated by the actual object referred by x variable.
Don’t worry if you haven't understood it completely by the above definition as we are going to explore it more using an example.
Consider a hierarchy of 3 classes A, B and C where C extends B and B extends A. Also consider a statement:

B b = new C();

Now the statement

b instanceof A

will return true as b (which is actually an instance of Class C) is an instance of subclass of A. similarly statements

b instanceof B

b instanceof C

will also return true for the same reason. But note that if b would be an instance of Class B (i.e. the above expression would be B b = new B()), the last statement i.e. b instanceof C would have returned false as instance of B is neither C nor a subclass of C.
Now consider the statement:


This actually means: can an instance of class A be assigned to reference type of C (note that b.getClass() is C class no B)? In syntactical way, this means: can we write C c = new A()? And we know this is not true. Thus the above statement will return false. Similarly for the statement b.getClass().isAssignableFrom(B.class) will also return false because C c = new B() is incorrect. But the statement


will return true as C c = new C() is a correct statement.

I hope this concised explanation will make the difference very clear.


Sagar Misal said...

Very useful one.First time came to know about isAssignableFrom()

John Alert said...

Hi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.. I am a regular follower of your blog. Really very informative post you shared here. Kindly keep blogging. If anyone wants to become a Java developer learn from Java EE Online Training from India. or learn thru Java EE Online Training from India . Nowadays Java has tons of job opportunities on various vertical industry.