Main Page

Previous Next

Using the final Modifier

We have already used the keyword final 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 - as it must be defined in a subclass.

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 step that prevents the functionality of the class being extended by derivation, so you should be very sure that you want to do this.

Previous Next
JavaScript Editor Java Tutorials Free JavaScript Editor