Yes. Inheritance allows a child class to acquire accessible attributes and methods from a parent class, so shared code is defined once in the parent and reused by its children.
In object-oriented programming, the parent is the superclass, while the child is the subclass. The subclass establishes an “is-a” relationship with the superclass: for example, a Car is a Vehicle.
class Vehicle {
protected int speed;
public void move() {
System.out.println("Vehicle is moving");
}
}
class Car extends Vehicle {
public void openBoot() {
System.out.println("Boot opened");
}
}
Because Car extends Vehicle, a Car object can use the inherited speed attribute and move() method without those members being rewritten:
Car c = new Car();
c.speed = 50;
c.move();
c.openBoot();
The child can use inheritance in three main ways:
| Mechanism | Effect in the child class |
|---|---|
| Inherit | Reuses accessible attributes and methods unchanged |
| Extend | Adds new attributes or methods, such as openBoot() |
| Override | Replaces an inherited method with a specialized implementation using the same method signature |
For example, Car could override move() to print "Car is driving". When move() is called on a Car object, the overridden child version runs. This supports polymorphism, because different subclasses can respond differently to the same method call.
A common misconception is that a subclass directly accesses every member of its parent. Members declared private are not directly accessible from the subclass; they are normally accessed through inherited public or protected methods. Constructors are also used to initialize objects rather than being inherited like ordinary methods.
Exam technique: For IB Computer Science HL B3.2, define inheritance, identify the superclass and subclass, and explain exactly what is reused. In code-tracing questions, check whether a method is inherited or overridden before stating which implementation executes.