Java OCA OCP Practice Question 2611

Question

What is the result of the following code?

public class Main { 
   String walk = "walk,"; 
   static class InnerClass extends Main { 
      String walk = "toddle,"; 
   } /*from ww w . jav a 2  s  .co m*/
   public static void main(String[] args) { 
      Main f = new InnerClass(); 
      InnerClass b = new InnerClass(); 
      System.out.println(f.walk); 
      System.out.println(b.walk); 
   } 
} 
  • A. toddle,toddle,
  • B. toddle,walk,
  • C. walk,toddle,
  • D. walk,walk,
  • E. The code does not compile.
  • F. A runtime exception is thrown.


C.

Note

Both objects are InnerClass objects.

Virtual method invocation says that the subclass method gets called at runtime rather than the type in the variable reference.

However, we are not calling methods here.

We are referring to instance variables.

With instance variables, the reference type does matter.




PreviousNext

Related