Java OCA OCP Practice Question 835

Question

What will the following code print when run?

class MyClass  { 
    public int h = 4; 
    public int m ()  { 
        System .out.println ("MyClass " + h); 
        return h; 
     } /* w w  w . ja  va2  s  . com*/
} 

public class Main extends MyClass  { 
    public int h = 99; 
    public int m ()  { 
        System .out.println ("Main " + h); 
        return h; 
     } 
    public static void main (String [] args)  { 
        MyClass b = new Main (); 
        System .out.println (b .h + " " + b .m ()); 
        Main bb =  (Main) b; 
        System .out.println (bb .h + " " + bb .m ()); 
     } 
} 

Select 1 option

A. Main 99 /*from   w  ww  . j av  a  2s  .  c  o m*/
   4 99 
   MyClass 99 
   99 99 

B. MyClass 99 
   4 99 
   Main 99 
   99 99 

C. Main 99 
   4 99 
   Main 99 
   4 99 
   
D. Main 99 
   4 99 
   Main 99 
   99 99 


Correct Option is  : D

Note

Methods are overridden and variables are shadowed.

b refers to an object of class Main so b.m () will always call the overridden (subclass's method).

The type of reference of b is MyClass. so b.h will always refer to MyClass's h.

Inside Main's m (), Main's h will be accessed instead of MyClass's h because you are accessing this.h ('this' is implicit) and the type of this is Main.




PreviousNext

Related