Loading subject…
Inheritance
Inheritance is a fundamental concept in object-oriented programming (OOP) that allows a class (subclass/child) to reuse and extend the attributes and methods of another class (superclass/parent).
It promotes code reusability, cuts duplication, and sets up a hierarchical relationship between classes.
Java: the keyword is extends, and super(...) runs the parent constructor first.
class Vehicle { protected String fuelType; // subclasses may use this private int serialNumber; // subclasses may not
public Vehicle(String fuelType) { this.fuelType = fuelType; }
public void move() { System.out.println("Vehicle is moving"); }
public int getSerialNumber() { return serialNumber; }}
class Aeroplane extends Vehicle { private int wingspan;
public Aeroplane(String fuelType, int wingspan) { super(fuelType); // initialises the inherited part this.wingspan = wingspan; }
public void fly() { System.out.println("Flying on " + fuelType); }}
public class TestInheritance { public static void main(String[] args) { Aeroplane a = new Aeroplane("kerosene", 60); a.move(); // inherited method a.fly(); // subclass method }}Python: the parent goes in brackets after the class name, and super().__init__(...) does the same job.
class Vehicle: def __init__(self, fuel_type): self._fuel_type = fuel_type # one underscore: treat as protected self.__serial_number = 0 # two underscores: name mangled
def move(self): print("Vehicle is moving")
def get_serial_number(self): return self.__serial_number
class Aeroplane(Vehicle): def __init__(self, fuel_type, wingspan): super().__init__(fuel_type) # initialises the inherited part self.wingspan = wingspan
def fly(self): print("Flying on", self._fuel_type)
a = Aeroplane("kerosene", 60)a.move() # inherited methoda.fly() # subclass methodThese lines sit inside Aeroplane, the subclass of Vehicle defined above.
class Aeroplane extends Vehicle { public void report() { System.out.println(fuelType); // protected: compiles // System.out.println(serialNumber); // private: will not compile System.out.println(getSerialNumber()); // public method reaches it }}class Aeroplane(Vehicle): def report(self): print(self._fuel_type) # one underscore: still reachable # print(self.__serial_number) # AttributeError: name mangled print(self.get_serial_number()) # public method reaches it