When you extend a class, all subclasses inherit the methods of the superclass. Additionally, the subclasses may have additional (more specific) methods that the superclass does not have.
What method you can call depends only on the type of the variable. When you have a variable of superclass type, you can store instances of the subclasses with this variable (Polymorphism). You have a reference to this subclass object, but you cannot use the specific subclass methods with the variable of the superclass.
But if you are sure that the instance referenced by the variable is really a subclass object, you can cast and apply the more specific method.
Here PalmTree has a more specific method (with the coconuts). Only PalmTree variables can invoke this method, not general Plants. If you have a class that uses this class, e.g.
Therefore the bold line when uncommented would not work. The plant-method works for all plant instances (and shows polymorphy due to overiding as in the alga). If you want to invoke a PalmTree specific method, you can cast and invoke the palm-specific method as in the lines in italics. The instanceof check is necessary to avoid ClassCastExceptions.
Hi Hassel, I am not getting following block of code from your post. How plant can be an instance of palmTree? plant is superclass of palmTree. Or I am missing something? Please explain me this concept as I am not good in casting related questions. Your explaination would help me.
prints three times "true". You must understand the instanceof operator checking if the object refered by the variable is an instance (an object) of the type asked for. In the above example variable "plant" is of type Plant, but you can assign also subtypes of Plant to this variable. With the instanceof operator, you can check which one hides behind the variable.