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| German | English | Meaning |
|---|---|---|
| Oberklasse, Elternklasse | superclass, parent class, base class | is inherited from |
| Unterklasse, Kindklasse | subclass, child class, derived class | inherits |
- 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 Carasks whether the object is aCar. - Only one parent class: Interfaces solve behavior from several sources.
See also: extends, Inheritance, Multiple inheritance