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:

check.png 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.

check.png 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.

check.png private methods are automatically considered final.

That makes sense; after all, a subclass can’t override a method that it can’t see.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset