-1

Can anybody explain why output to below question is "A.test" ?

class A {

   private void test(){

      System.out.println("A.test");

   }

   public void mytest(){

      this.test();

   }

}

class B extends A{

   protected void test(){

      System.out.println("B.test");

   }

}

public class Test{

   public static void main(String[] args) {

      A a = new B();

      a.mytest();

   }

}
XtremeBaumer
  • 6,275
  • 3
  • 19
  • 65

2 Answers2

2

The test() method of class A cannot be overridden by class B, since it is private. Therefore this.test(); invokes A's test() method even though it is executed on an instance of class B.

Eran
  • 387,369
  • 54
  • 702
  • 768
0

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.

nits.kk
  • 5,204
  • 4
  • 33
  • 55