DEV Community

Nanthini Ammu
Nanthini Ammu

Posted on

Java Inheritance

What is Inheritance?

  • Inheritance is a mechanism where one class gets the states and behaviors of another class.
  • inheritance is: is-a relationship. That is, we use inheritance only if there is a is-a relationship between two classes.

Example:
Car is a Vehicle
Orange is a Fruit
Surgeon is a Doctor
Dog is an Animal
Developer is an Employee

  • We can say, A child class uses features of a parent class.

What is Superclass and Subclass?

  • Child class is called as subclass and the parent class is called as superclass.

What keyword is used to implement Inheritance?

  • The extends keyword is used to perform inheritance in Java.

Superclass:

public class Employee {

    int employeeID;
    int salary;

    public static void main(String[] args) {

    }

    public void work()
    {
        System.out.println("Employee work");
    }
}

Subclass:

public class Developer extends Employee {


    public static void main(String[] args) {
        Developer d1 = new Developer();

        d1.employeeID = 18426;
        d1.salary = 400000;
        System.out.println(d1.employeeID);
        System.out.println(d1.salary);
        d1.work();
        d1.devWork();
    }

    public void devWork(){
        System.out.println("Coding");
    }


}
Enter fullscreen mode Exit fullscreen mode

Why do we use Inheritance?

  • Code reuse
  • Avoid duplication
  • Easy maintenance
  • Builds relationship between classes

What are the types of inheritance?

  • Single Inheritance
  • Multilevel Inheritance
  • Hierarchical Inheritance
  • Multiple Inheritance
  • Hybrid Inheritance

Example with Real world scenario:

Employee → Developer

  • Employee is a general concept.
  • Developer is a specific type of employee.
  • In real life, every developer is an employee, but not every employee is a developer.

Why inheritance?

  • Common properties like id, name, salary belong to Employee.
  • Developer gets them automatically and adds its own behavior.

Important point :

  • Developer inherits employee properties using extends.

Vehicle → Car

  • Vehicle is a parent (common features).
  • Car is a child (specialized vehicle).
  • Bike, car, bus are all vehicles.

Why inheritance?

  • Avoid rewriting common logic like start().
  • Child class focuses only on extra features.

Bank → SavingsAccount

  • Bank provides common services.
  • SavingsAccount is one specific account type.
  • All accounts follow bank rules, but savings account has extra features.

Why inheritance?

  • Common banking behavior in parent.
  • Specific account rules in child.

Top comments (0)