Private methods in Inheritance
Solution 1:
Private methods are only for the owner.
Not even for the kids, relatives or friends of the owner.
Solution 2:
You answered it yourself. As the private methods are not inherited, a superclass reference calls its own private method.
Solution 3:
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.
Solution 4:
Superclass obj = new Subclass();
At this point, obj
is both things, a Subclass
, and a Superclass
object. The fact that you use Superclass
in the declaration of the variable is just a matter of casting it.
When you do: obj.doSomething()
, you are telling the compiler to call the private method doSomething()
of obj
. Because you are doing it from the main static method inside Superclass
, the compiler can call it.
If you would use the main method of Subclass
rather than the one in Superclass
, you would not be able to access that method because, as you said, it's neither inherited nor a part of your definition of Subclass
.
So basically you understood inheritance correctly. The problem was related to the visibility of private methods.
Solution 5:
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"