Java Inheritance Example

Inheritance is the process by which one object acquires the properties of another object.

Inheritance - IS-A relationship between a superclass and its subclasses. The process where one object acquires the properties of another object plus it can have its own.

In Java, Inheritance is achieved using the extends keyword.

Java Inheritance Example

Employee class (parent class) can define the common logic of any employee in the software company, while another class named Programmer can extend Employee to reuse the common logic and add logic specific to the programmer.

Let's create an Employee class with the following code:
public class Employee {

    private String name;
    
    public Employee(String name) {
        this.name = name;        
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }   
}
Let's create a Programmer class that extends the Employee class:

public class Programmer extends Employee {

    private String team;

    public Programmer(String name, String team) {
        super(name);
        this.team = team;
    }

    public String getTeam() {
        return team;
    }

    public void setTeam(String team) {
        this.team = team;
    }
}
Let's test this logic with the main() method:
public class Main {

    public static void main(String[] args) {

        Programmer p = new Programmer("John", "R&D");
        
        String name = p.getName();
        String team = p.getTeam();
        
        System.out.println(name + " is assigned to the " + team + " team");
    }
}
Output:
John is assigned to the R&D team

Related Java OOPS Examples


Comments