Firstly, it's helpful to think of the "instanceof" operator as indicating an "IS-A" relationship. It's always true that a subclass object IS-A superclass object, but it's not always true that a superclass object IS-A subclass object. For example: a Banana is always a Fruit, but a Fruit isn't always a Banana.
In the code you provided, the method m2 looks like this:
For the sake of discussion, let's also assume that there exist two more classes:
When m2 gets invoked, you don't necessarily know that "a" is an All instance. You only know that "a" is an All reference... but in Java, a reference can point to an instance of any subclass of its reference type. So "a" can be an instance of All, an instance of Bll, or even an instance of Cll or Bmm. However, because m2 wants to do something with "a" that's specific to Bll and Bll's subclasses, it therefore performs the instanceof check to filter out the cases where "a" is actually an instance of All or Bmm. Remember: a Bll instance IS-A Bll and a Cll instance IS-A Bll, but an All instance is not a Bll and a Bmm is not a Bll.
Another way of looking at it: a subclass has all the visible methods of the superclass, but a superclass need not have all the visible methods of its subclasses. A superclass instance therefore isn't an instance of a subclass, because you can't always invoke a subclass method on a superclass instance.
Hope this helps a little. Do feel free to ask if you have any further questions! [ November 13, 2007: Message edited by: Kelvin Lim ]
Joined: Dec 05, 2006
Thank you very much kelvin,it helped me a lot. Nice explaination