Java OCA OCP Practice Question 2696

Question

Consider the following program and predict the output:

class Base {/*ww w . j a  v a2s . co  m*/
       public void print() {
               System.out.println("Base");
       }
}

class Derived extends Base {
       public void print() {
               System.out.println("Derived");
       }
}

class Main {
       public static void main(String args[]) {
               Base obj1 = new Derived();
               Base obj2 = (Base)obj1;
               obj1.print();
               obj2.print();
       }
}

a) Derived/*w ww .j  av a  2 s.  co  m*/
   Derived

b) Base
   Derived

c) Derived
   Base

d) Base
   Base


a)

Note

The dynamic type of the instance variable obj2 remains the same (i.e., Derived).

Thus, when print() is called on obj2, it calls the derived class version of the method.




PreviousNext

Related