Join Regular Classroom : Visit ClassroomTech

Use of final in Inheritance in java

Using final to Prevent Overriding

While method overriding is one of Java’s most powerful features, there will be times when you will want to prevent it from occurring. To disallow a method from being overridden, specify final as a modifier at the start of its declaration. Methods declared as final cannot be overridden. The following fragment illustrates final:

/* JAVA program to understand to use of final in Inheritance  */
/* www.codewindow.in */
class A 
{
    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!");
        
    }
}

Because meth( ) is declared as final, it cannot be overridden in B. If you attempt to do so, a compile-time error will result.

Using final to Prevent Inheritance

Sometimes you will want to prevent a class from being inherited. To do this, precede the class declaration with final. Declaring a class as final implicitly declares all of its methods as final, too.

Here is an example of a final class:

/* JAVA program to understand to using final to Prevent Inheritance  */
/* www.codewindow.in */
final class A 
{
// ...
}
// The following class is illegal.
class B extends A
{ // ERROR! Can't subclass A
// ...
}

it is illegal for B to inherit A since A is declared as final.