Final Classes & Methods
Home ] Up ] What is Inheritance? ] Inheritance versus Containment ] Superclasses & Subclasses ] Visibility Modifiers & Inheritance ] [ Final Classes & Methods ] Polymorphism ] Data Hiding & Encapsulation ] Abstract Classes ] Interfaces ] Cloning Objects ] The Collections Framework ] Interfaces & Callbacks ]

 

 

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.

 

This page was last modified on 02 October, 2007