JavaObject-oriented programmingInheritance and polymorphism

Inheritance

3 seconds read

Extending classes

Inheritance is a mechanism to derive a new class from another class (base class). The new class acquires some fields and methods of the base class. Inheritance is one of the important principles of the object-oriented programming allowing developers to build convenient class hierarchies and reuse the existing code.

There are several terms. A class that is derived from another class is called a subclass (also it's known as a derived class, extended class or child class). The class from which the subclass is derived is called superclass (also a base class or a parent class).

To derive a new class from another class the keyword extends is used. The common syntax is shown below.

class SuperClass { }

class SubClassA extends SuperClass { }

class SubClassB extends SuperClass { }

class SubClassC extends SubClassA { }

Some important points:

  • Java doesn't support multiple-classes inheritance that means a class can inherit from a single superclass;
  • a class hierarchy can have multiple levels (class C can extend class B that extend class A);
  • a superclass can have more than one subclasses.

A subclass inherits all public and protected fields and methods from the superclass. Also, a subclass can add new fields and methods. The inherited and added members will be used in the same way.

A subclass doesn't inherit private fields and methods from the superclass. However, if the superclass has public or protected methods for accessing its private fields, these members can be used inside the subclasses.

Constructors are not inherited by subclasses, but the superclass's constructor can be invoked from the subclass using the special keyword super. This keyword is considered in another topic.

If you'd like the base class members will be accessible from all subclasses but not accessible from outside code (excluding the same package), use the access modifier protected.

Inheritance represents the IS-A relationship. A base class represents a general thing and subclass represents a particular thing.

An example of class hierarchy

Let's consider a more useful sample. A telecommunication company serves clients. It has a small staff consisting only of managers and programmers. Here is a class hierarchy for people connected with the company's activities including clients to store them in a database.

At the first, we present the hierarchy in the drawing form. An arrow means one class extends another one.

The class hierarchy for the telecommunication company
  • the base class Person has fields for storing common data: name, year of birth, and address;
  • the class Client has additional fields to store contract number and status (gold or not);
  • the class Employee stores the start date of work for the company and salary;
  • the class Programmer has an array of the used programming languages;
  • the class Manager may have a dazzling smile.

Let's see the code:

class Person {
    protected String name;
    protected int yearOfBirth;
    protected String address;

    // public getters and setters for all fields here
}

class Client extends Person {
    protected String contractNumber;
    protected boolean gold;

    // public getters and setters for all fields here
}

class Employee extends Person {
    protected Date startDate;
    protected Long salary;

    // public getters and setters for all fields here
}

class Programmer extends Employee {
    protected String[] programmingLanguages;

    public String[] getProgrammingLanguages() {
        return programmingLanguages;
    }

    public void setProgrammingLanguages(String[] programmingLanguages) {
        this.programmingLanguages = programmingLanguages;
    }
}

class Manager extends Employee {
    protected boolean smile;

    public boolean isSmile() {
        return smile;
    }

    public void setSmile(boolean smile) {
        this.smile = smile;
    }
}

This hierarchy has two levels and five classes overall. All fields are protected that means they are visible to subclasses. Also, each class has public getters and setters but some are skipped for short.

Let's create an object of the Programmer class and fill the inherited fields using the inherited setters. To read values of the fields we can use inherited getters.

Programmer p = new Programmer();

p.setName("John Elephant");
p.setYearOfBirth(1985);
p.setAddress("Some street, 15");
p.setStartDate(new Date());
p.setSalary(500_000L);
p.setProgrammingLanguages(new String[] { "Java", "Scala", "Kotlin" });

System.out.println(p.getName()); // John Elephant
System.out.println(p.getSalary()); // 500000
System.out.println(Arrays.toString(p.getProgrammingLanguages())); // [Java, Scala, Kotlin]

We also can create an instance of any class included in the considered hierarchy.

So, inheritance provides a powerful mechanism for code reuse and writing convenient hierarchies. Many things of the real world can be simulated like hierarchies from general to particular concept.

Final classes

If the class declared with the keyword final, it cannot have subclasses.

final class SuperClass { }

If you'll try to extend the class, the compile-time error will happen.

Some standard classes are declared as final: Integer, Long, String, Math. They cannot be extended.

How did you like the theory?
Report a typo