Java methods and overriding — what happens when a subclass attempts to override a final method?\n\nclass A \n{\n final public int GetResult(int a, int b) { return 0; }\n}\nclass B extends A \n{\n public int GetResult(int a, int b) { return 1; }\n}\npublic class Test \n{\n public static void main(String args[]) \n { \n B b = new B();\n System.out.println("x = " + b.GetResult(0, 1));\n }\n}\n\nChoose the correct outcome.

Difficulty: Easy

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.

More Questions from Declarations and Access Control

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion