Here\'s an interesting code snippet:
public class Superclass {
public static void main (String[] args){
Superclass obj = new Subclass();
It works because you are casting to a Superclass
from within a method of the Superclass
. In that context, Superclass.doSomething
is available to the compiler.
If you were to change your super and subclasses to two different arbitrary classes A and B, not related to the class containing the main
method, and try the same code, the compiler would complain about not having access to the method.
Since the reference type of the object obj
is SuperClass
, a call to doSomething()
tries to access the private method defined in SuperClass
itself (private methods cannot be overridden).
As doSomething()
is accessible within SuperClass
, the main
method can call doSomething()
without giving any error/s.
Hope this helps! :-)
When you used this line:
Superclass obj = new Subclass();
You casted Subclass into a Superclass Object, which uses only the methods of the Superclass and the same data. If you casted it back into a Subclass, you could use the Subclass methods again, like so:
((Subclass)obj).doSomething(); #prints "from Subclass"