What is the output of the following Java program A09?

Solution:

class BaseTest   
{  
  void print()  
  {  
    System.out.println("BaseTest:print() called");  
  }  
}  
public class Test extends BaseTest   
{  
  void print()   
  {  
    System.out.println("Test:print() called");  
  }  
  public static void main (String args[])  
  {  
    BaseTest b = new Test();  
    b.print();  
  }  
}  

Output

  Test:print() called

Explanation

It is an example of Dynamic method dispatch. The type of reference variable b is determined at runtime. At compile-time, it is checked whether that method is present in the Base class. In this case, it is overridden in the child class, therefore, at runtime the derived class method is called.

0 answers