Super class can invoke the methods of the sub class without using typecasting, without using reflection and without using a reference other than this
only if they are overridden.
In your case A a = new B();
, object of B
is created which has both the behaviours private void test()
as inherited by super class A
as well as protected void test()
as added by B
. The reason for both the methods being there and not just one is that due to the acess modifier being private
the method is not visible in subclass scope. Hence it can not overriden and adding the method with same name just simply adds another method.
As there is no run time polymorphism in this case hence compile time target method is resolved and method defined in A
is invoked.
If in case you would have overriden the mytest
in B
and from the overriden mytest
you would have made a call to test
then method in B
would have been invoked. This is easy to understand as any method of B
can not see any private
method of its super class.