What Is Inheritance In Java?

By Faruque Ahamed Mollick

Inheritance in Java is a process where a Java class get the properties of another class. The properties can be methods and fields. With the inheritance process in Java, the information is made manageable in a hierarchical order.

The class which inherits the properties of the other class is called subclass. It is also known as child class. And the class whose properties are inherited to subclass is called superclass or parent class.

See the simple structure of code below which shows you the superclass and subclass.:

class SuperClass {
   ...
   ...
   ...
}
class SubClass extends SuperClass {
   ...
   ...
   ...
}

In the above code structure, SuperClass class is the parent class and the class SubClass is the child class.

Now I am going to show you a code so that you will understand the real purpose of using inheritance.

Inheritance example in Java

Below is the example Java code where you can see the parent class Person is inherited by its subclass Student:

public class Person{
  private int age;
  private String name;
  
  public void setAge(int a) {
    age=a;
  }
    public void setName(String n) {
    name=n;
  }
  
  public int getAge() {
    return(age);
  }
    public String getName() {
    return(name);
  }
}



public class Student extends Person {
  private int rollNo;
  public void setrollNo(int roll) {
    rollNo=roll;
  }
  public int getrollNo() {
    return(rollNo);
  }
}

In the above code, all the properties of Person class are now available in Student class.

Now look at the below code example:

public class Get {
  public static void main(String [] args) {
    Student p1= new Student();
    p1.setAge(15);
    p1.setrollNo(10895);
    p1.setName("Faruque Ahamed");
    System.out.println("Age is " +p1.getAge());
    System.out.println("Roll No is " +p1.getrollNo());
    System.out.println("Name: " +p1.getName());
  }
  
}

It will return you the given result:

 

Age is 15

Roll No is 10895

Name: Faruque Ahamed

So you can see that we can call all the properties from Person class via Student class as all the properties of Person class is available in Student class.

So in student class, you have not work for creating the age and name again. This is the real purpose of using inheritance in Java. Inheritance will help you to avoid rework.

Leave a Reply

Your email address will not be published. Required fields are marked *