Java methods and overriding — what happens when a subclass attempts to override a final method? class A { final public int GetResult(int a, int b) { return 0; } } class B extends A { public int GetResult(int a, int b) { return 1; } } public class Test { public static void main(String args[]) { B b = new B(); System.out.println("x = " + b.GetResult(0, 1)); } } Choose the correct outcome.
-
Ax = 0
-
Bx = 1
-
CCompilation fails.
-
DAn exception is thrown at runtime.
Answer
Correct Answer: Compilation fails.
Explanation
Introduction / Context:This question targets the rule that methods declared final cannot be overridden in subclasses. It asks what happens when a subclass B declares a method with the same signature as a final method in superclass A.
Given Data / Assumptions:
- A declares final public int GetResult(int,int).
- B extends A and declares public int GetResult(int,int) with a different body.
- Main constructs B and calls the method, but compilation must succeed before runtime.
Concept / Approach:In Java, the final modifier on an instance method prevents overriding in any subclass. Declaring a method in B with the exact same signature attempts to override the final method and violates the language rule, causing a compile-time error. The program never runs.
Step-by-Step Solution:
Identify the final method: A.GetResult(int,int).B declares the same signature, so it is an attempted override.The compiler reports an error such as "Cannot override the final method from A".Therefore, there is no runtime output.Verification / Alternative check:Change B’s method name or remove final in A; compilation would then succeed, producing output based on the chosen implementation.
Why Other Options Are Wrong:
- Outputs "x = 0" or "x = 1" presume successful compilation.
- A runtime exception is irrelevant; the code fails earlier at compile time.
Common Pitfalls:Confusing final with static or private: private methods are not overridden but hidden; final prohibits overriding.
Final Answer:Compilation fails.