Java - Inheritance in Java

What is Inheritance?

Inheritance can reuse code from an existing class when creating a new class.

The new class is called a subclass and the existing class is called the superclass.

A superclass has the reused code and customized by the subclass.

The subclass inherits from the superclass. A superclass is also called as a base class or a parent class.

A subclass is also known as a derived class or a child class.

Syntax

To inherit a class from another class, use the keyword extends followed by the superclass name.

The general syntax is

<class modifiers> class SubclassName extends <SuperclassName> {

}

For example, the following code declares a class MySub, which inherits from class MySuper:

public class MySub extends MySuper {

}

Real Inheritance

Let's look at an example of inheritance in Java.

Let's start with an Employee class as listed in Listing 16-1.

Demo

class Employee {
  private String name = "Unknown";

  public void setName(String name) {
    this.name = name;
  }/*from  w  w w  .j  av  a 2 s . com*/

  public String getName() {
    return name;
  }
}

// Manager class inherits from the Employee class.
// The Manager class does not contain any code, except the declaration.

class Manager extends Employee {
  // No code is needed for now
}

public class Main {
  public static void main(String[] args) {
    // Create an object of the Manager class
    Manager mgr = new Manager();

    // Set the name of the manager
    mgr.setName("Mary");

    // Get the name of the manager
    String mgrName = mgr.getName();

    // Display the manager name
    System.out.println("Manager Name: " + mgrName);

    Employee emp = new Employee();
    emp.setName("Tom");
    String empName = emp.getName();
    System.out.println("Employee Name: " + empName);

  }
}

Result

Note

Even if the body Manager class is empty, it works the same as the Employee class, because it inherits from the Employee class.

You create a manager object by using the Manager class's constructor.

Manager mgr = new Manager();

When a class inherits from another class, it inherits its superclass members (instance variables, methods, etc.).

Related Topics