Using final with Inheritance: final Methods, final Classes & Performance
1. Topic Introduction
Inheritance is powerful, but sometimes an architect intentionally locks a method's security check or locks an entire class (like java.lang.String) so nobody can create malicious or buggy subclasses. The **final keyword** gives you that exact lock at three levels: constants, methods, and classes.
Imagine designing a government currency note. You mark the watermark formula as **final method ('subclasses may exist, but NOBODY may alter how authenticity is verified!') or mark the entire blueprint final class** ('NOBODY may extend or subclass this blueprint at all!'). That's why Java marks java.lang.String and Integer as final class—preventing anyone from subclassing String to break security or immutability!
final: (1) final variable = constant; (2) final method = prevents overriding; (3) final class = prevents inheritance.3. Essential Exam Definitions
final Methodfinal modifier (final void verify()) that CANNOT be overridden by any subclass, ensuring consistent behavior and allowing early binding optimization.final Classfinal modifier (final class SecurityGate) that CANNOT be inherited (subclassed) by any other class; all its methods are implicitly final.4. Detailed Technical Explanation & Syntax
Three Uses of final (Summary & Rules)
1. **final Variables**: Create named constants (cannot be reassigned).
2. **final Methods (Preventing Overriding)**: Placed on critical methods whose contract/algorithm must never be altered by subclasses. Bonus benefit: because a final method can never be overridden, the JVM/JIT knows at compile/load time that dynamic lookup isn't needed and can safely inline small final calls for extra performance!
3. **final Classes (Preventing Inheritance)**: Adding final before class blocks extends completely (class Sub extends FinalClass is a COMPILE ERROR). Because no subclass can exist, every method inside a final class is implicitly final (no overriding possible).
Incompatibility with abstract: A class or method can NEVER be both final and abstract, because abstract REQUIRES inheritance/overriding while final FORBIDS both!
5. Working Principle: Compiler Checks for final in Inheritance
- If
Subattempts@Overrideon afinalmethod ofSuper,javacaborts with:overridden method is final. - If
Subwritesextends FinalClass,javacaborts with:cannot inherit from final FinalClass.
7. Complete Java Code Examples & Tracing
final security method inside an extendable class (overriding blocked) and a final class (extends blocked).| 1 | class ExamRules { |
| 2 | final void printStrictRule() { |
| 3 | System.out.println("Rule: No electronic devices permitted in hall."); |
| 4 | } |
| 5 | |
| 6 | void greeting() { |
| 7 | System.out.println("Welcome to KTU Exam Hall."); |
| 8 | } |
| 9 | } |
| 10 | |
| 11 | class LabExamRules extends ExamRules { |
| 12 | // void printStrictRule() {} // COMPILE ERROR: cannot override final method! |
| 13 | |
| 14 | @Override |
| 15 | void greeting() { // Valid: greeting() is NOT final |
| 16 | System.out.println("Welcome to Programming Lab."); |
| 17 | } |
| 18 | } |
| 19 | |
| 20 | final class ImmutableConfig { |
| 21 | final String scheme = "KTU 2024"; |
| 22 | void show() { |
| 23 | System.out.println("Locked Config: " + scheme); |
| 24 | } |
| 25 | } |
| 26 | |
| 27 | // class CustomConfig extends ImmutableConfig {} // COMPILE ERROR: cannot inherit from final class! |
| 28 | |
| 29 | public class FinalInheritanceDemo { |
| 30 | public static void main(String[] args) { |
| 31 | LabExamRules lab = new LabExamRules(); |
| 32 | lab.printStrictRule(); |
| 33 | lab.greeting(); |
| 34 | |
| 35 | ImmutableConfig cfg = new ImmutableConfig(); |
| 36 | cfg.show(); |
| 37 | } |
| 38 | } |
Rule: No electronic devices permitted in hall. Welcome to Programming Lab. Locked Config: KTU 2024
finalextendsclass@Override- Confusing
final(keyword blocking change/inheritance),finally(exception cleanup block), andfinalize()(deprecated Object GC hook). - Marking an
abstract classasfinal.
Real-World Applications
java.lang.String,java.lang.System,java.lang.Math, and Wrapper classes (Integer,Double) are allfinalclasses in the JDK for security and immutability.
Important KTU Exam Points
- Always state all 3 uses of
final: Variable (constant), Method (prevent overriding), Class (prevent inheritance). - Give real JDK examples of
finalclasses (String,Math,Integer).
Memory Techniques & Revision
final3 Locks:final var= No Reassign;final method()= No Override;final class= No Subclass!
Common Pitfalls to Avoid
- Thinking a
finalclass cannot have fields updated—objects of afinalclass can still have non-final mutable fields unless the fields themselves arefinal!
KTU-Style Questions & Exam-Ready Answers
Structured specifically for KTU Part A (3-mark) and Part B (6/9-mark) evaluation rubrics.
- 1.
finalVariable: Creates a constant whose value cannot be changed after initialization (final double PI = 3.14;). - 2.
finalMethod: Prevents subclasses from overriding a critical method (final void check()) and allows early binding optimization. - 3.
finalClass: Prevents any class from inheriting/extending it (final class String), ensuring immutability and security.
Quick Understanding Check
1. Which declaration is ILLEGAL in Java?