Java ProgramsOOPFinal Class

Final Class in Java

beginner·  OOP  ·  Modifiers

Problem

A class declared final can be used and instantiated normally, but Java refuses to compile any class that tries to extend it — the same guarantee that keeps java.lang.String's behavior fixed.

Define a final TaxCalculator class and use it normally, without ever needing to subclass it.

Input
new TaxCalculator().calculateTax(1000.0)
Output
Tax: 200.0

Java Program

Java
final class TaxCalculator { double calculateTax(double income) { return income * 0.2; } } public class FinalClassDemo { public static void main(String[] args) { TaxCalculator calc = new TaxCalculator(); System.out.println("Tax: " + calc.calculateTax(1000.0)); // class SpecialTaxCalculator extends TaxCalculator {} would not compile } }

Output

Tax: 200.0

Core Logic

Adding the final modifier to the class declaration itself locks its implementation in place, so no subclass can ever override how it behaves.

How It Works
  1. 1final class TaxCalculator is used exactly like any ordinary class — created with new, its methods called normally.
  2. 2calculateTax(1000.0) runs the one implementation this class defines, with no possibility of a subclass swapping in different behavior.
  3. 3Writing class SpecialTaxCalculator extends TaxCalculator anywhere in the codebase would fail to compile, since final forbids it outright.
  4. 4This is a compile-time guarantee, not a runtime check — the restriction is enforced before the program ever runs.
new TaxCalculator().calculateTax(1000.0) prints "Tax: 200.0", using the one and only implementation this class will ever have.
💡

Key Point: final is most useful when a class's exact behavior must never be altered by inheritance — java.lang.String itself is final for precisely this reason, so no code anywhere can subtly change what a String does.

Key Concepts

final classprevent inheritancefixed behavior

Related Programs