Object Oriented Programming: Unit II: Inheritance, Packages and Interfaces

The Final with Inheritance

with Example Java Programs

A variable can be declared as final. If a particular variable is declared as final then it cannot be modified further. The final variable is always a constant.

The Final with Inheritance

The final keyword can be applied at three places -

• For declaring variables

• For declaring the methods

• For declaring the class

Final Variables and Methods

A variable can be declared as final. If a particular variable is declared as final then it cannot be modified further. The final variable is always a constant. For example

final int a = 10;

The final keyword can also be applied to the method. When final keyword is applied to the method, the method overriding is avoided. That means the methods those are declared with the keyword final cannot be overridden.

Consider the following Java program which makes use of the keyword final for declaring the method

class Test

{

final void fun()

{

System.out.println("\n Hello, this function declared using final");

}

}

class Test1 extends Test

{

final void fun()

{

System.out.println("\n Hello, this another function");

}

}

Output

D:\>javac Test.java

Test.java:10: fun() in Test1 cannot override fun() in Test; overridden method is final final void fun() absido bene

1 error

Program Explanation

The above program, on execution shows the error. Because the method fun is declared with the keyword final and it cannot be overridden in derived class.

Final Classes to Stop Inheritance

If we declare particular class as final, no class can be derived from it. Following Java program is an example of final classes.

final class Test

{

void fun()

{

System.out.println("\n Hello, this function in base class");

}

}

class Test1 extends Test

{

final void fun()

{

System.out.println("\n Hello, this another function");

}

}

Output

D:\>javac Test.java

Test.java:8: cannot inherit from final Test

class Test1 extends Test

1 error

Review Question

1. Write a note on final keyword.

Object Oriented Programming: Unit II: Inheritance, Packages and Interfaces : Tag: : with Example Java Programs - The Final with Inheritance