Final Methods

Final methods are an interesting feature of Java. They allow you to make a class partially final without preventing its inheritance by another class. To make a method final, use the final keyword on the declaration, as shown in Example 2-20.

Example 2-20. A final method
package oracle.hcj.finalstory;
public class FinalMethod {
 public final void someMethod( ) {
 }
}


This declaration is the antithesis of the abstract keyword. Whereas the abstract keyword declares that subclasses must override the method, the final keyword guarantees that the method can never be overridden by subclasses. Subclasses can inherit from the FinalMethod class and can override any method other than someMethod( ). You should never make a method final unless it must be final. When in doubt, leave the final keyword off a method. After all, you never know the kinds of variations the users of your class may come up with. One example of a situation in which making a method final is the proper route to take is when a read-only property is used. Example 2-21 shows an example of such a property.

Example 2-21. A final property
package oracle.hcj.finalstory;
public class FinalMethod {
 /** A demo property. */
 private final String name;
 protected FinalMethod(final String name) {
 this.name = name;
 }
 public final String getName( ) {
 return this.name;
 }
}


In this example, the name property is set at construction time and can never be changed. Also, you have defined that you never want a subclass to hide this property (which it could by declaring its own name property if getName( ) wasn't final). This is a good reason to make a method final. By making getName( ) a final method, you can guarantee that the user of subclasses of this object will always call this method when she executes getName( ). In the JDK, the method getClass( ) in java.lang.Object is final for this very reason.

      
Comments