Learn
B3.2.1 | INHERITANCE AND REUSE (HL ONLY)
01 | EXTEND A WORKING IDEA
The Device class already validates an ID, keeps battery state and provides a controlled use_power operation. A robot also needs these capabilities, but it adds scanning behaviour. Copying the entire Device implementation into Robot would duplicate rules that could later drift apart.
Inheritance allows a more specific class to reuse and extend behaviour through a more general class. Robot can specialize Device while keeping the existing power-use contract.
This HL-only lesson explains the hierarchy, constructs Python and Java subclasses, and examines public, private, protected and package access. The next lesson develops polymorphism and overriding further.
02 | SUPERCLASS AND SUBCLASS
| Role | Meaning | Example |
|---|---|---|
| Superclass / parent / base class | The more general definition supplying reusable behaviour | Device |
| Subclass / child / derived class | A specialization extending that definition | Robot |
| Instance | A particular object created from a class | Robot D01 |
A Robot is a Device in this model. It should be usable for the Device operations its callers expect, while offering extra robot-specific behaviour.
The relationship concerns class definitions. A Robot object is not made by creating a separate parent object beside a separate child object; initialization establishes the relevant state on the same instance.
03 | APPLY THE IS-A TEST
A Robot can be a Device because the model treats robots as devices with identifiers, charge and power-use operations. A Tablet could be another Device specialization.
A Robot has a Motor, but a Robot is not a kind of Motor. Object collaboration is normally a better representation for that relationship.
Do not use inheritance simply because two classes both store a string named name. Shared spelling alone does not establish a compatible conceptual contract.
04 | READ THE UML GENERALIZATION
Follow the arrow upward to the more general class. The child boxes need not repeat every inherited operation to communicate reuse.
Tablet is an illustrative second specialization, not a claim that every device system needs that subclass. Add it only if the requirements justify it.
05 | REUSE THE VALIDATED BASE CLASS
class Device:
def __init__(self, device_id, battery=100):
if not isinstance(device_id, str) or not device_id.strip():
raise ValueError("Device ID required")
if type(battery) is not int or not 0 <= battery <= 100:
raise ValueError("Battery must be an integer from 0 to 100")
self._device_id = device_id.strip()
self._battery = battery
@property
def battery(self):
return self._battery
def use_power(self, amount):
if type(amount) is not int or amount < 0 or amount > self._battery:
return False
self._battery = self._battery - amount
return True
def describe(self):
return f"{self._device_id}: battery {self._battery}%"
This base class owns the device ID and battery representation. use_power validates before changing charge and returns False without mutation on a rejected request.
Its battery property is read-only through normal public assignment. Python underscores still signal convention rather than enforced Java-style private access.
A subclass should use the controlled operation when consuming power instead of rewriting the validation logic or directly subtracting from _battery.
06 | THE SIMPLEST PYTHON SUBCLASS
class Device:
def __init__(self, device_id, battery=100):
if not isinstance(device_id, str) or not device_id.strip():
raise ValueError("Device ID required")
if type(battery) is not int or not 0 <= battery <= 100:
raise ValueError("Battery must be an integer from 0 to 100")
self._device_id = device_id.strip()
self._battery = battery
@property
def battery(self):
return self._battery
def use_power(self, amount):
if type(amount) is not int or amount < 0 or amount > self._battery:
return False
self._battery = self._battery - amount
return True
def describe(self):
return f"{self._device_id}: battery {self._battery}%"
class Tablet(Device):
pass
tablet = Tablet("T01", 60)
print(tablet.battery)
print(tablet.use_power(10))
print(tablet.describe())
Outputs: 60, True, T01: battery 50%. Tablet defines no new initializer or methods, so normal lookup finds the inherited behaviour. pass supplies an empty class body in this example.
This demonstrates the mechanism, not a reason to create an otherwise unnecessary subclass in a real application.
07 | ADD ROBOT-SPECIFIC STATE
class Device:
def __init__(self, device_id, battery=100):
if not isinstance(device_id, str) or not device_id.strip():
raise ValueError("Device ID required")
if type(battery) is not int or not 0 <= battery <= 100:
raise ValueError("Battery must be an integer from 0 to 100")
self._device_id = device_id.strip()
self._battery = battery
@property
def battery(self):
return self._battery
def use_power(self, amount):
if type(amount) is not int or amount < 0 or amount > self._battery:
return False
self._battery = self._battery - amount
return True
def describe(self):
return f"{self._device_id}: battery {self._battery}%"
class Robot(Device):
def __init__(self, device_id, battery=100):
super().__init__(device_id, battery)
self._scans = 0
@property
def scans(self):
return self._scans
def scan(self):
if not self.use_power(10):
return False
self._scans = self._scans + 1
return True
def describe(self):
return f"{super().describe()}; scans {self._scans}"
class Robot(Device) declares the inheritance relationship. Robot’s initializer calls the inherited initialization route, then establishes its own _scans = 0 state.
Robot inherits battery and use_power, adds scans and scan, and overrides describe. This combines reuse, extension and specialization rather than copying Device’s whole implementation.
The full listing is self-contained: save it before constructing Robot instances in later examples.
08 | SUPER DOES NOT CONSTRUCT A SECOND DEVICE
In this single-inheritance example, super().__init__(device_id, battery) invokes the next initializer through the method-resolution order, which is Device.__init__. It operates on the same receiving Robot object.
Device initializes _device_id and _battery; control returns to Robot’s initializer, which creates _scans. The caller receives one initialized Robot instance.
super() is not a separate parent instance. Its general meaning is lookup through the method-resolution order; describing it simply as “always call the direct parent” becomes misleading in more complex multiple-inheritance designs.
09 | TRACE INITIALIZATION IN ORDER
| Stage for Robot("R01", 30) | Receiver | Effect |
|---|---|---|
| Enter Robot.__init__ | One new Robot instance | Parameters available; robot-specific state not yet assigned |
| Call super().__init__ | Same Robot instance | Device validates input and assigns ID/battery |
| Resume Robot.__init__ | Same Robot instance | Assign _scans = 0 |
| Construction succeeds | Caller obtains the instance | battery 30; scans 0 |
If the base initializer raises for battery 150, the later _scans assignment is not reached and the construction expression does not complete normally.
Forgetting super initialization can leave inherited methods without the attributes they need, even though the class definition itself is syntactically valid.
10 | EXTEND BEHAVIOUR THROUGH A VALIDATED OPERATION
Robot.scan requests self.use_power(10). If the inherited operation returns False, scan returns False without incrementing scans. If it succeeds, scan increments its own counter and returns True.
A robot with battery 15 can scan once, leaving battery 5 and scans 1. Its next scan is rejected and preserves both values.
The scan is a simulated action counted by this example. Actual hardware control, sensor failure and physical success would need additional rules and cannot be established merely by subtracting a percentage.
11 | RUN THE COMPLETE SPECIALIZATION
class Device:
def __init__(self, device_id, battery=100):
if not isinstance(device_id, str) or not device_id.strip():
raise ValueError("Device ID required")
if type(battery) is not int or not 0 <= battery <= 100:
raise ValueError("Battery must be an integer from 0 to 100")
self._device_id = device_id.strip()
self._battery = battery
@property
def battery(self):
return self._battery
def use_power(self, amount):
if type(amount) is not int or amount < 0 or amount > self._battery:
return False
self._battery = self._battery - amount
return True
def describe(self):
return f"{self._device_id}: battery {self._battery}%"
class Robot(Device):
def __init__(self, device_id, battery=100):
super().__init__(device_id, battery)
self._scans = 0
@property
def scans(self):
return self._scans
def scan(self):
if not self.use_power(10):
return False
self._scans = self._scans + 1
return True
def describe(self):
return f"{super().describe()}; scans {self._scans}"
robot = Robot("R01", 15)
print(robot.scan())
print(robot.scan())
print(robot.battery, robot.scans)
print(robot.describe())
Outputs: True, False, 5 1, then R01: battery 5%; scans 1. The power validation was reused rather than duplicated in scan.
Calling inherited use_power directly on the Robot is also valid under its base contract. It consumes charge without incrementing scans, because not every power use is a scan.
12 | OVERRIDE WHILE REUSING THE GENERAL DESCRIPTION
Robot defines its own describe with the same expected result kind: a description string. Its implementation calls super().describe() to obtain the reusable device description, then appends scan information.
This is overriding: a subclass supplies its own implementation of an inherited operation. It differs from adding scan, which is a new operation in this model.
Keeping the original description construction in Device avoids duplicating ID/battery formatting. The next lesson explores how callers select overridden methods through polymorphism.
13 | INTERACTIVE: FOLLOW INHERITED AND ADDED WORK
Step through a fixed Python execution. The trace names the operation used and separates inherited battery state from Robot’s added scan counter. Device initialization and Robot initialization act on each same instance.
Predict whether the next operation changes battery, scans or both. A rejected scan should change neither. A direct inherited use_power call changes charge but does not invent a scan event.
14 | PRIVATE JAVA STATE: REUSE THROUGH OPERATIONS
Java private members are not inherited as accessible subclass members. A subclass cannot simply write battery if that field is private in a separately declared base class.
A Robot instance still contains the base-defined state, and inherited public operations can manage it. Calling usePower or getBattery is different from directly accessing the private field.
Private access can be permitted within an enclosing nest under Java rules, so nested teaching examples can obscure this boundary. The complete Java program below uses separate top-level classes to keep the restriction clear.
15 | PUBLIC, PROTECTED AND PACKAGE ACCESS
| Java member access | Subclass in same package | Subclass in a different package |
|---|---|---|
| public | Accessible, subject to containing-type visibility | Accessible, subject to containing-type/module visibility |
| protected | Accessible within package | Accessible in subclass code, with receiver restrictions for instance access |
| No modifier: package access | Accessible within the declaring package | Not accessible as a package-private member from outside that package |
| private | Not accessible merely because it is a subclass | Not accessible merely because it is a subclass |
Protected is not “public to every object from any package”. Outside the declaring package, a subclass’s access to a protected instance member must use the permitted subclass-related receiver; an arbitrary base-class reference does not gain access just because the access site is a subclass.
These are member-level summaries. Containing-type access and other Java rules still apply. See the Java Language Specification on protected access for the precise qualified-access rules.
16 | JAVA: A COMPLETE REUSE EXAMPLE
class Device {
private final String deviceId;
private int battery;
public Device(String deviceId, int battery) {
if (deviceId == null || deviceId.trim().isEmpty()
|| battery < 0 || battery > 100) {
throw new IllegalArgumentException("Invalid device state");
}
this.deviceId = deviceId.trim();
this.battery = battery;
}
public int getBattery() {
return battery;
}
public boolean usePower(int amount) {
if (amount < 0 || amount > battery) {
return false;
}
battery -= amount;
return true;
}
protected String label() {
return deviceId;
}
public String describe() {
return label() + ": battery " + battery + "%";
}
}
class Robot extends Device {
private int scans;
public Robot(String deviceId, int battery) {
super(deviceId, battery);
scans = 0;
}
public boolean scan() {
if (!usePower(10)) {
return false;
}
scans++;
return true;
}
public String scanReport() {
return label() + ": scans " + scans;
}
@Override
public String describe() {
return super.describe() + "; scans " + scans;
}
}
public class InheritanceExample {
public static void main(String[] args) {
Robot robot = new Robot("R01", 15);
System.out.println(robot.scan());
System.out.println(robot.scan());
System.out.println(robot.describe());
System.out.println(robot.scanReport());
}
}
Save as InheritanceExample.java. Outputs: true, false, R01: battery 5%; scans 1, and R01: scans 1. Robot reuses public usePower and protected label without directly accessing Device’s private fields.
extends declares specialization. super(deviceId, battery) initializes the base-defined state. @Override lets the compiler check that describe genuinely overrides an inherited method with a compatible declaration.
17 | CONSTRUCTORS ARE NOT ORDINARY INHERITED METHODS
Java constructors are not inherited. A Robot constructor explicitly delegates to an appropriate superclass constructor; if no explicit constructor invocation is supplied, ordinary rules can insert a no-argument super call, which only works when a suitable accessible constructor exists.
Python can inherit __init__ through method lookup when the subclass defines no initializer, as Tablet did. If the subclass defines its own initializer, it must arrange any required base initialization explicitly in this design.
Do not assume that adding a subclass field somehow initializes it automatically under the application’s rules. Establish a complete valid state before normal construction finishes.
18 | PYTHON ACCESS CONVENTIONS STILL APPLY
Robot can technically access Device’s _battery because the underscore is a non-public convention rather than an enforced private modifier. This lesson still uses use_power to preserve the base class’s validation contract.
A double-leading-underscore field defined as __battery in Device is name-mangled for Device. Writing self.__battery inside Robot would normally refer to a different mangled name, not a safe direct route to the base’s field.
Expose an appropriate operation when subclasses need controlled access. Avoid depending on mangled backing names as the normal design interface.
19 | A SUBCLASS SHOULD KEEP THE BASE PROMISE
If Device.use_power rejects unaffordable requests without changing charge, Robot should not redefine it to allow a negative battery while claiming to support the same contract.
A subclass should remain usable where the base operation is expected. Extra features should extend the model without surprising base callers or invalidating established state rules.
A poorly chosen hierarchy may fail this test. Do not force a class into a parent relationship when it must disable fundamental parent behaviour to work.
20 | REUSE DOES NOT MEAN SHARED INSTANCE STATE
class Device:
def __init__(self, device_id, battery=100):
if not isinstance(device_id, str) or not device_id.strip():
raise ValueError("Device ID required")
if type(battery) is not int or not 0 <= battery <= 100:
raise ValueError("Battery must be an integer from 0 to 100")
self._device_id = device_id.strip()
self._battery = battery
@property
def battery(self):
return self._battery
def use_power(self, amount):
if type(amount) is not int or amount < 0 or amount > self._battery:
return False
self._battery = self._battery - amount
return True
def describe(self):
return f"{self._device_id}: battery {self._battery}%"
class Robot(Device):
def __init__(self, device_id, battery=100):
super().__init__(device_id, battery)
self._scans = 0
@property
def scans(self):
return self._scans
def scan(self):
if not self.use_power(10):
return False
self._scans = self._scans + 1
return True
def describe(self):
return f"{super().describe()}; scans {self._scans}"
a = Robot("R01", 30)
b = Robot("R02", 50)
a.scan()
print(a.battery, a.scans)
print(b.battery, b.scans)
print(isinstance(a, Robot), isinstance(a, Device))
Outputs: 20 1, 50 0, then True True. Each object owns its own inherited and added instance state. Reusing the implementation does not combine both robots’ charge or scan count.
isinstance confirms that the subclass object can be recognized as both its specific type and its base type. It does not create another object.
21 | REUSE THROUGH CHANGE, WITH TESTS
If power validation is duplicated in five device classes, a change may be implemented inconsistently. A suitable shared base operation offers one place for the common rule and lets subclass operations reuse it.
That shared dependency also carries risk: a base change can affect every subclass. Test the base contract and each subclass behaviour that relies on it, including rejected requests.
Changing an internal representation is easier when subclasses use the intended interface instead of editing protected or conventionally non-public fields everywhere. Prefer the narrowest useful extension surface.
22 | WHEN INHERITANCE ADDS TOO MUCH COUPLING
Deep hierarchies can make it hard to locate which implementation runs. A base class exposing many mutable protected fields can make every subclass depend on its storage layout.
A parent built only to avoid a few similar lines may combine unrelated responsibilities. The resulting hierarchy can be harder to change than separate focused functions or collaborating objects.
Use a meaningful shared contract and a small, understandable hierarchy. Reuse is a benefit when the reused behaviour actually belongs to the shared model.
23 | INHERITANCE VERSUS COLLABORATION
A Robot is a Device in this example, but a Robot has a Sensor. A sensor can be held as a referenced component and asked for readings, rather than making Robot inherit Sensor.
Collaboration can also reuse behaviour through contained objects. It introduces interfaces and coordination of its own, so it is not automatically the answer to every design.
The later HL objective on composition and aggregation examines relationship meanings in more detail. For now, distinguish a type specialization from simply using another object’s capability.
24 | CONSTRUCT IT: A CAMERA SPECIALIZATION
Construct Camera as a Device subclass. It starts with photos = 0. take_photo consumes 5 percentage points only when affordable and increments photos only after that power use succeeds.
Reveal one Python implementation
class Device:
def __init__(self, device_id, battery=100):
if not isinstance(device_id, str) or not device_id.strip():
raise ValueError("Device ID required")
if type(battery) is not int or not 0 <= battery <= 100:
raise ValueError("Battery must be an integer from 0 to 100")
self._device_id = device_id.strip()
self._battery = battery
@property
def battery(self):
return self._battery
def use_power(self, amount):
if type(amount) is not int or amount < 0 or amount > self._battery:
return False
self._battery = self._battery - amount
return True
def describe(self):
return f"{self._device_id}: battery {self._battery}%"
class Camera(Device):
def __init__(self, device_id, battery=100):
super().__init__(device_id, battery)
self._photos = 0
@property
def photos(self):
return self._photos
def take_photo(self):
if not self.use_power(5):
return False
self._photos = self._photos + 1
return True
camera = Camera("C01", 7)
print(camera.take_photo())
print(camera.take_photo())
print(camera.battery, camera.photos)
Outputs: True, False, 2 1. The subclass adds its own counter and operation while reusing the validated base method.
25 | COMMON INHERITANCE ERRORS
| Error | Repair |
|---|---|
| Copy all base methods into each subclass | Reuse an appropriate inherited implementation |
| Assume super creates another parent object | It invokes behaviour on the same receiver through the lookup order |
| Forget required base initialization | Delegate to the appropriate initialization route |
| Directly edit a Java private base field | Use an accessible base operation or designed extension point |
| Treat protected as unrestricted public access | Apply package/subclass and receiver rules |
| Assume Python underscore enforces Java access | Respect the convention while explaining the language difference |
| Increment scan count before testing power success | Change added state only after the shared operation succeeds |
| Use inheritance for every has-a link | Choose relationship semantics from the model |
26 | EXPLAIN AND APPLY REUSABILITY
Explain the shared contract, identify what the subclass inherits, and connect reuse to reduced duplication and consistent rule changes. Then acknowledge dependencies and test obligations.
To Apply, construct the base and subclass declarations, initialize both shared and added state, reuse an accessible operation, and show a successful and rejected run. State access rules in the language actually used.
For example: “scan calls inherited use_power rather than subtracting charge independently, therefore it reuses the same validation and preserves battery bounds. If the request fails, scans stays unchanged.”