Java OCA OCP Practice Question 685

Question

Which statement regarding the following code is correct?

class MyBaseClass { 
   public int i = 10; 
   private int j = 20; 

} 

class MyClass extends MyBaseClass { 
   private int i = 30; //1 
   public int k = 40; 

} 

class MySubClass extends MyClass{ 
} 

public class Main{ 
   public static void main (String args []){ 
      MySubClass c = new MySubClass (); 
      System.out.println (c.i); //2 
      System.out.println (c.j); //3 
      System.out.println (c.k);  
    } //from  www  .j  a v a2 s  .c o  m
} 

Select 1 option

  • A. It will print 10 and 40 if //3 is commented.
  • B. It will print 40 if //2 and //3 are commented.
  • C. It will not compile because of //1.
  • D. It will compile if //2 is commented.
  • E. None of these.



    Correct Option is  : B

    Note

    You cannot access c.i because i is private in MyClass.

    But you can access ((MyBaseClass)c).i because i is public in MyBaseClass.

    Remember that member variables are shadowed and not overridden.

    So, MyClass's i shadows MyBaseClass's i and since MyClass's i is private, you can't access MyBaseClass's i unless you cast the reference to MyBaseClass.

    You cannot access c.j because j is private in MyBaseClass.




    PreviousNext

    Related