What is the output of the following Java program no. 10?

  1. class Base
  2. {
  3.     public void baseMethod()
  4.     {
  5.         System.out.println(“BaseMethod called …”);
  6.     }
  7. }
  8. class Derived extends Base
  9. {
  10.     public void baseMethod()
  11.     {
  12.         System.out.println(“Derived method called …”);
  13.     }
  14. }
  15. public class Test
  16. {
  17.     public static void main (String args[])
  18.     {
  19.         Base b = new Derived();
  20.         b.baseMethod();
  21.     }
  22. }

Output

Derived method called ...

Explanation

The method of Base class, i.e., baseMethod() is overridden in Derived class. In Test class, the reference variable b (of type Base class) refers to the instance of the Derived class. Here, Runtime polymorphism is achieved between class Base and Derived. At compile time, the presence of method baseMethod checked in Base class, If it presence then the program compiled otherwise the compiler error will be shown. In this case, baseMethod is present in Base class; therefore, it is compiled successfully. However, at runtime, It checks whether the baseMethod has been overridden by Derived class, if so then the Derived class method is called otherwise Base class method is called. In this case, the Derived class overrides the baseMethod; therefore, the Derived class method is called.