Java OCA OCP Practice Question 1273

Question

What is the output of the following application?

package mypkg; /*ww  w .  j  a va  2 s .  c  o  m*/
? 
class Shape { 
   protected int weight = 3; 
   private int height = 5; 
   public int getWeight() { return weight; } 
   public int getHeight() { return height; } 
} 
? 
public class Main extends Shape { 
   public int weight = 2; 
   public int height = 4; 
   public void printDetails() { 
      System.out.print(super.getWeight()+","+super.height); 
   } 
   public static final void main(String[] fuel) { 
      new Main().printDetails(); 
   } 
} 
  • A. 2,5
  • B. 3,4
  • C. 3,5
  • D. The code does not compile.


D.

Note

The code does not compile because super.height is not visible in the Main class, making Option D the correct answer.

Even though the Main class defines a height value, the super keyword looks for an inherited version.

Since there are none, the code does not compile.

Note that super.getWeight() returns 3 from the variable in the parent class, as polymorphism and overriding does not apply to instance variables.




PreviousNext

Related