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.
Get Java For Dummies Quick Reference now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.