Home »
Java programming language
Using final keyword with inheritance in Java
Java | using final with inheritance: In this tutorial, we are going to learn how to use final keyword with inheritance in java?
By Preeti Jain Last updated : March 23, 2024
final keyword with inheritance in java
- The final keyword is final that is we cannot change.
- We can use final keywords for variables, methods, and class.
- If we use the final keyword for the inheritance that is if we declare any method with the final keyword in the base class so the implementation of the final method will be the same as in derived class.
- We can declare the final method in any subclass for which we want that if any other class extends this subclass.
Case 1: Declare final variable with inheritance
// Declaring Parent class
class Parent {
/* Creation of final variable pa of string type i.e
the value of this variable is fixed throughout all
the derived classes or not overidden*/
final String pa = "Hello , We are in parent class variable";
}
// Declaring Child class by extending Parent class
class Child extends Parent {
/* Creation of variable ch of string type i.e
the value of this variable is not fixed throughout all
the derived classes or overidden*/
String ch = "Hello , We are in child class variable";
}
class Test {
public static void main(String[] args) {
// Creation of Parent class object
Parent p = new Parent();
// Calling a variable pa by parent object
System.out.println(p.pa);
// Creation of Child class object
Child c = new Child();
// Calling a variable ch by Child object
System.out.println(c.ch);
// Calling a variable pa by Child object
System.out.println(c.pa);
}
}
Output
D:\Programs>javac Test.java
D:\Programs>java Test
Hello , We are in parent class variable
Hello , We are in child class variable
Hello , We are in parent class variable
Case 2: Declare final methods with inheritance
// Declaring Parent class
class Parent {
/* Creation of final method parent of void type i.e
the implementation of this method is fixed throughout
all the derived classes or not overidden*/
final void parent() {
System.out.println("Hello , we are in parent method");
}
}
// Declaring Child class by extending Parent class
class Child extends Parent {
/* Creation of final method child of void type i.e
the implementation of this method is not fixed throughout
all the derived classes or not overidden*/
void child() {
System.out.println("Hello , we are in child method");
}
}
class Test {
public static void main(String[] args) {
// Creation of Parent class object
Parent p = new Parent();
// Calling a method parent() by parent object
p.parent();
// Creation of Child class object
Child c = new Child();
// Calling a method child() by Child class object
c.child();
// Calling a method parent() by child object
c.parent();
}
}
Output
D:\Programs>javac Test.java
D:\Programs>java Test
Hello , we are in parent method
Hello , we are in child method
Hello , we are in parent method