Java OCA OCP Practice Question 1602

Question

Given the following classes, what will be the output of compiling and running the class Main?

class Printable{
   public void print ()  {  System.out.println ("Printable: print");    }
}

public class Main extends Printable{
   public void print ()  {  System.out.println ("Main: print");    }
   public static void main  (String args  []){
      Printable  a = new Printable ();
      Main t  = new Main ();
      a.print (); //1
      t.print (); //2
      a = t;     //3
      a.print (); //4
    }//from   w w  w.  j  av  a  2 s  . c o m
}

Select 1 option

  • A. Compiler error at line 3.
  • B. Runtime error at line 3.
  • C. It will print:
  • Printable: print
  • Main: print
  • Printable: print
  • D. It will print:
  • Printable: print
  • Main: print
  • Main: print
  • E. It will print:
  • Printable: print
  • Printable: print
  • Printable: print


Correct Option is  : D

Note

Since Main is a subclass of Printable, a = t will be valid at compile time as well runtime.

But a cast is needed to make for t = (Main) a;

This will be ok at compile time but if at run time 'a' does not refer to an object of class Main then a ClassCastException will be thrown.

Now, method to be executed is decided at run time and it depends on the actual class of object referred to by the variable.

Here, at line 4, variable a refers to an object of class Main.

So Main's print () will be called which prints Main: print.

This is polymorphism in action!.




PreviousNext

Related