Java final keyword with Inheritance

Using final to Prevent Overriding

To disallow a method from being overridden, add final as its modifier.

Methods declared as final cannot be overridden.

class A {/* w  w w . j a  va  2s  .c  o m*/
  final void meth() {
    System.out.println("This is a final method.");
  }
}

class B extends A {
  void meth() { // ERROR! Can't override.
    System.out.println("Illegal!");
  }
}

Using final to Prevent Inheritance

To prevent a class from being inherited, add final to class declaration.

Declaring a class as final declares all of its methods as final.

We cannot declare a class as both abstract and final since an abstract class has to be extended by its subclasses.

Here is an example of a final class:

final class A {
  // ...
}

// The following class is illegal.
class B extends A { // ERROR! Can't subclass A
  // ...
}



PreviousNext

Related