EMZETT.
Login

Parent class and child class

In short: In inheritance, the parent class (superclass, base class) is the class that is inherited from. The child class (subclass, derived class) inherits and can extend.

In more detail: The terms only describe the roles in an “is-a” relationship. A Car (child) is a Vehicle (parent). The same class can be both at once: parent for some, child for others.

In Depth

class Vehicle {                           // parent / superclass
    protected int wheels;
    Vehicle(int wheels) { this.wheels = wheels; }
    void start() { System.out.println("Vehicle starts"); }
}
 
class Car extends Vehicle {               // child / subclass
    Car() { super(4); }
    @Override void start() { super.start(); System.out.println("Engine on"); }
}
 
class SportsCar extends Car { }           // child of Car, grandchild of Vehicle
GermanEnglishMeaning
Oberklasse, Elternklassesuperclass, parent class, base classis inherited from
Unterklasse, Kindklassesubclass, child class, derived classinherits
  • Hierarchy: A class hierarchy is a tree. At the very top in Java is always Object.
  • What the child gets: All non-private attributes and methods. It may override methods and add new ones.
  • Constructor chain: When a child is created, the parent’s constructor runs first (super(...)).
  • Type compatibility: Vehicle v = new Car(); is allowed (upcast). The reverse needs a cast: Car c = (Car) v;, which can fail at runtime.
  • Checking: v instanceof Car asks whether the object is a Car.
  • Only one parent class: Interfaces solve behavior from several sources.

See also: extends, Inheritance, Multiple inheritance