Final classes: Preventing Inheritance

Sometimes, you will wish to prevent someone from deriving a class from one of your classes.

A class that cannot be used as a superclass is called a final class.

To specify that a class is final, you use the final keyword:

public final class President extends Employee
{
    // ...
}

Final methods

It is also possible to declare a specific method in a class final, meaning that no subclass can override that method.

All methods in a final class are automatically final.

Reasons for making classes or methods final

  1. Efficiency
    Dynamic binding is expensive. If the compiler knows that a method will not be overridden, it can optimize calls to that method (by inlining it, etc.)
  2. Safety
    By disabling dynamic binding, you can remove a lot of uncertainty from your code.

Final fields (data)

Remember that final data members of a class, once initialized, cannot be changed.  Class constants are typically static final fields.