DEV Community

Cover image for Preventing Extending and Overriding
Paul Ngugi
Paul Ngugi

Posted on

Preventing Extending and Overriding

Neither a final class nor a final method can be extended. A final data field is a constant. You may occasionally want to prevent classes from being extended. In such cases, use the final modifier to indicate that a class is final and cannot be a parent class. The Math class is a final class. The String, StringBuilder, and StringBuffer classes are also final classes. For example, the following class A is final and cannot be extended:

public final class A {
// Data fields, constructors, and methods omitted
}

You also can define a method to be final; a final method cannot be overridden by its subclasses.
For example, the following method m is final and cannot be overridden:

public class Test {
// Data fields, constructors, and methods omitted
public final void m() {
// Do something
}
}

The modifiers public, protected, private, static, abstract, and final are used on classes and class members (data and methods), except that the final modifier can also be used on local variables in a method. A final local variable is a constant inside a method.

Top comments (0)