final Method
A final
method is a method that can’t be overridden by a subclass. To create a final method, you simply add the keyword final to the method declaration. For example:
public class SpaceShip
{
public final int getVelocity()
{
return this.velocity;
}
}
Here, the method getVelocity is declared as final. Thus, any class that uses the SpaceShip class as a base class can’t override the getVelocity method. If it tries, the compiler issues the error message (Overridden method final).
Here are some additional details about final methods:
Generally, you should avoid declaring final methods. Although you might think that a subclass wouldn’t need to override a method, you can’t always be sure what someone else might want to do with your class.
final methods execute a bit more efficiently than non-final methods because the compiler knows at compile time that a call to a final method won’t be overridden by some other method.
private methods are automatically considered final.
That makes sense; after all, a subclass can’t override a method that it can’t see.
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access