Java OCA OCP Practice Question 1317

Question

What is the output of the following application?

class Math { 
   public final double secret = 2; 
} 
class MyBase extends Math { 
   public final double secret = 4; 
} 
public class Main extends MyBase { 
   public final double secret = 8; 
   public static void main(String[] numbers) { 
      Math math = new Main(); 
      System.out.print(math.secret); 
   } /*from   w w w  .  j  av  a 2  s.c  o  m*/
} 
  • A. 2
  • B. 4
  • C. 8
  • D. The code does not compile.


A.

Note

The code compiles without issue, so Option D is incorrect.

Java allows methods to be overridden, but not variables.

Marking them final does not prevent them from being reimplemented in a subclass.

Polymorphism does not apply in the same way it would to methods as it does to variables.

In particular, the reference type determines the version of the secret variable that is selected, making the output 2.

Option A the correct answer.




PreviousNext

Related