Inheritance (extends), super Keyword & Constructor Delegation
1Concept
Inheritance models an IS-A relationship where a subclass inherits state and behavior from a superclass. Subclasses use `super(...)` to invoke the superclass constructor, which MUST execute before subclass field initialization to guarantee proper parent state setup.
2Architecture Diagram
Hierarchy:
[ Superclass: Device ] (fields: id, brand)
^
|
[ Subclass: Laptop ] (fields: ramGb, os) ---> Invokes super(id, brand)3Code Example
Core Java
public class InheritanceDemo {
static class Device {
protected String brand;
public Device(String brand) {
this.brand = brand;
System.out.println("Superclass constructor: Device initialized.");
}
}
static class Laptop extends Device {
private int ramGb;
public Laptop(String brand, int ramGb) {
super(brand); // Delegates to parent constructor
this.ramGb = ramGb;
System.out.println("Subclass constructor: Laptop initialized with " + ramGb + "GB RAM.");
}
}
public static void main(String[] args) {
Laptop laptop = new Laptop("Dell", 32);
}
}4Expected Output
Superclass constructor: Device initialized. Subclass constructor: Laptop initialized with 32GB RAM.
5Key Takeaways
- ✓Java supports single class inheritance; a class can only extend one direct superclass.
- ✓If parent has no no-arg constructor, child constructor MUST explicitly invoke `super(args)`.
- ✓Constructors are NOT inherited by subclasses.