Home »
Java programming language
Inheritance and its implementation in Java
In this tutorial, we are going to learn what is inheritance in java, how to implement inheritance in java? We will study inheritance with example in Java.
Submitted by Preeti Jain, on June 02, 2019
Java Inheritance
- Inheritance in Java is a methodology by which a class allows to inherit the features of other class.
- It is also known as IS-A relationship.
- By using extends keyword we can implement inheritance in java.
- The advantage of inheritance is reusability of code.
Important terms related to inheritance:
- Parent class:
It is also known as a superclass or base class and the definition of the parent class is the class whose properties (or features) is inherited.
- Child class:
It is also known as a subclass or derived class and the definition of the child class is the class that inherits the properties (or features) of other class.
How to implement inheritance in java?
We implement inheritance with the help of extends keyword.
Syntax:
class Parent {
public void method1() {
// Fields and Statement
}
}
class Child extends Parent {
public void method2() {
// Fields and Statement
}
}
Example:
In below example of inheritance, class Parent is a superclass, class Child is a subclass which extends the Parent class.
/*Java program to demonstrate the
concept of inheritance */
// Parent class
class Parent {
// The Parent class has one method
// displayParentMessage() method to print message of Parent Class
public void displayParentMessage() {
System.out.println("Hello, we are in parent class method");
}
}
// Sub class or derived class
class Child extends Parent {
// The Child subclass adds one more method
// displayChildMessage() method to print message of Parent Class
public void displayChildMessage() {
System.out.println("Hello, we are in child class method");
}
}
// Main class in this class we will create
//object of parent and child class
class Main {
public static void main(String[] args) {
// Creation of Parent class object
Parent p = new Parent();
// Calling Parent class method by Parent class object
p.displayParentMessage();
// Creation of Child class object
Child c = new Child();
// Calling Child class method by Child class object
c.displayChildMessage();
// Calling Parent class method by Child class object
c.displayParentMessage();
}
}
Output
D:\Programs>javac Main.java
D:\Programs>java Main
Hello, we are in parent class method
Hello, we are in child class method
Hello, we are in parent class method