Java OCA OCP Practice Question 1435

Question

What will be the result of compiling and running the following code?

class Base{ //  w  ww  .  j a  v  a2s . com
   public Object getValue (){ return new Object ();  } //1 
} 

class Base2 extends Base{ 
   public String getValue (){ return "hello";  } //2 
} 

public class Main{ 
   public static void main (String [] args){ 
      Base b = new Base2 (); 
      System.out.println (b .getValue ()); //3 
    } 
} 

Select 1 option

  • A. It will print the hash code of the object.
  • B. It will print hello.
  • C. Compile time error at //1.
  • D. Compile time error at //2.
  • E. Compile time error at //3.


Correct Option is  : B

Note

Observe that at run time b points to an object of class Base2.

Base2 overrides getValue().

Therefore, Base2's getValue() will be invoked and it will return hello.




PreviousNext

Related