6.12. Using the final Modifier

You have already used the final keyword to fix the value of a static data member of a class. You can also apply this keyword to the definition of a method, and to the definition of a class.

It may be that you want to prevent a subclass from overriding a method in your class. When this is the case, simply declare that method as final. Any attempt to override a final method in a subclass will result in the compiler flagging the new method as an error. For example, you could declare the method addPoint() as final within the class PolyLine by writing its definition in the class as:

public final void addPoint(Point point) {
      ListPoint newEnd = new ListPoint(point);  // Create a new ListPoint
      end.setNext(newEnd);             // Set next variable for old end as new end
      end = newEnd;                    // Store new point as end
   }

Any class derived from PolyLine would not be able to redefine this method. Obviously, an abstract method cannot be declared as final—because it must be defined in a subclass somewhere.

If you declare a class as final, you prevent any subclasses from being derived from it. To declare the class PolyLine as final, you would define it as:

public final class PolyLine {
   // Definition as before...
}

If you now attempt to define a class based on PolyLine, you will get an error message from the compiler. An abstract class cannot be declared as final since this would prevent the abstract methods in the class from ever being defined. Declaring a class as final is a drastic ...

Get Ivor Horton's Beginning Java™ 2, JDK™ 5th Edition 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.