Java OCA OCP Practice Question 1456

Question

What does the following print?

class MyCar extends Car { 
   String type = "sport"; 
} 
public class Car { 
   String type = "family"; 
   public static void main(String[] args) { 
      Car family = new MyCar(); 
      MyCar sport = new MyCar(); 
      System.out.print(family.type + "," + sport.type); 
   } //from w w w .ja  v  a2s  .com
} 
  • A. family,sport
  • B. sport,family
  • C. sport,sport
  • D. None of the above


A.

Note

While both objects are instances of MyCar, we are not calling methods in this example.

Virtual method invocation only works for methods, not instance variables.

For instance variables, Java actually looks at the type of the reference and calls the appropriate variable.

This makes each reference call a different class's instance variable in this example, and Option A is correct.




PreviousNext

Related