Inheritance
Inheritance is a mechanism where a new class (derived class or subclass) inherits attributes and methods from an existing class (base class or superclass). This allows you to create a hierarchy of classes that share common functionality while allowing specialization.
Understanding Inheritance
Section titled “Understanding Inheritance”Inheritance creates an “is-a” relationship. For example:
- A
Caris-aVehicle - A
Dogis-anAnimal - A
Manageris-anEmployee
Basic Inheritance
Section titled “Basic Inheritance”class Vehicle: """Base class (parent/superclass)""" def __init__(self, brand: str, model: str, year: int): self.brand = brand self.model = model self.year = year
def start(self): return f"{self.brand} {self.model} started."
def stop(self): return f"{self.brand} {self.model} stopped."
def get_info(self): return f"{self.brand} {self.model} ({self.year})"
class Car(Vehicle): """Derived class (child/subclass) - inherits from Vehicle""" def __init__(self, brand: str, model: str, year: int, num_doors: int): super().__init__(brand, model, year) # Call parent constructor self.num_doors = num_doors # Additional attribute
def honk(self): """New method specific to Car""" return "Beep beep!"
class Motorcycle(Vehicle): """Another derived class""" def __init__(self, brand: str, model: str, year: int, bike_type: str): super().__init__(brand, model, year) self.bike_type = bike_type # Additional attribute
def wheelie(self): """New method specific to Motorcycle""" return "Doing a wheelie!"
# Usagecar = Car("Toyota", "Camry", 2020, 4)print(car.start()) # Inherited method: "Toyota Camry started."print(car.honk()) # Car-specific method: "Beep beep!"print(car.get_info()) # Inherited method: "Toyota Camry (2020)"
motorcycle = Motorcycle("Yamaha", "YZF-R3", 2021, "Sport")print(motorcycle.start()) # Inherited method: "Yamaha YZF-R3 started."print(motorcycle.wheelie()) # Motorcycle-specific method: "Doing a wheelie!"// Base class (parent/superclass)public class Vehicle { protected String brand; protected String model; protected int year;
public Vehicle(String brand, String model, int year) { this.brand = brand; this.model = model; this.year = year; }
public String start() { return brand + " " + model + " started."; }
public String stop() { return brand + " " + model + " stopped."; }
public String getInfo() { return brand + " " + model + " (" + year + ")"; }}
// Derived class (child/subclass) - inherits from Vehiclepublic class Car extends Vehicle { private int numDoors;
public Car(String brand, String model, int year, int numDoors) { super(brand, model, year); // Call parent constructor this.numDoors = numDoors; // Additional attribute }
// New method specific to Car public String honk() { return "Beep beep!"; }}
// Another derived classpublic class Motorcycle extends Vehicle { private String bikeType;
public Motorcycle(String brand, String model, int year, String bikeType) { super(brand, model, year); this.bikeType = bikeType; // Additional attribute }
// New method specific to Motorcycle public String wheelie() { return "Doing a wheelie!"; }}
// Usagepublic class Main { public static void main(String[] args) { Car car = new Car("Toyota", "Camry", 2020, 4); System.out.println(car.start()); // Inherited method: "Toyota Camry started." System.out.println(car.honk()); // Car-specific method: "Beep beep!" System.out.println(car.getInfo()); // Inherited method: "Toyota Camry (2020)"
Motorcycle motorcycle = new Motorcycle("Yamaha", "YZF-R3", 2021, "Sport"); System.out.println(motorcycle.start()); // Inherited method: "Yamaha YZF-R3 started." System.out.println(motorcycle.wheelie()); // Motorcycle-specific method: "Doing a wheelie!" }}// Base class (parent/superclass)class Vehicle { protected brand: string; protected model: string; protected year: number;
constructor(brand: string, model: string, year: number) { this.brand = brand; this.model = model; this.year = year; }
start(): string { return `${this.brand} ${this.model} started.`; }
stop(): string { return `${this.brand} ${this.model} stopped.`; }
getInfo(): string { return `${this.brand} ${this.model} (${this.year})`; }}
// Derived class (child/subclass) - inherits from Vehicleclass Car extends Vehicle { private numDoors: number;
constructor(brand: string, model: string, year: number, numDoors: number) { super(brand, model, year); // Call parent constructor this.numDoors = numDoors; // Additional attribute }
honk(): string { return "Beep beep!"; }}
// Another derived classclass Motorcycle extends Vehicle { private bikeType: string;
constructor(brand: string, model: string, year: number, bikeType: string) { super(brand, model, year); this.bikeType = bikeType; // Additional attribute }
wheelie(): string { return "Doing a wheelie!"; }}
// Usageconst car = new Car("Toyota", "Camry", 2020, 4);console.log(car.start()); // Inherited method: "Toyota Camry started."console.log(car.honk()); // Car-specific method: "Beep beep!"console.log(car.getInfo()); // Inherited method: "Toyota Camry (2020)"
const motorcycle = new Motorcycle("Yamaha", "YZF-R3", 2021, "Sport");console.log(motorcycle.start()); // Inherited method: "Yamaha YZF-R3 started."console.log(motorcycle.wheelie()); // Motorcycle-specific method: "Doing a wheelie!"Toyota Camry started.Beep beep!Toyota Camry (2020)Yamaha YZF-R3 started.Doing a wheelie!#include <iostream>#include <string>
// Base class (parent/superclass)class Vehicle {protected: std::string brand; std::string model; int year;
public: Vehicle(const std::string& brand, const std::string& model, int year) : brand(brand), model(model), year(year) {}
std::string start() const { return brand + " " + model + " started."; }
std::string stop() const { return brand + " " + model + " stopped."; }
std::string getInfo() const { return brand + " " + model + " (" + std::to_string(year) + ")"; }};
// Derived class (child/subclass) - inherits from Vehicleclass Car : public Vehicle {private: int numDoors;
public: Car(const std::string& brand, const std::string& model, int year, int numDoors) : Vehicle(brand, model, year), numDoors(numDoors) {}
std::string honk() const { return "Beep beep!"; }};
// Another derived classclass Motorcycle : public Vehicle {private: std::string bikeType;
public: Motorcycle(const std::string& brand, const std::string& model, int year, const std::string& bikeType) : Vehicle(brand, model, year), bikeType(bikeType) {}
std::string wheelie() const { return "Doing a wheelie!"; }};
int main() { Car car("Toyota", "Camry", 2020, 4); std::cout << car.start() << std::endl; // Inherited method std::cout << car.honk() << std::endl; // Car-specific method std::cout << car.getInfo() << std::endl; // Inherited method
Motorcycle motorcycle("Yamaha", "YZF-R3", 2021, "Sport"); std::cout << motorcycle.start() << std::endl; // Inherited method std::cout << motorcycle.wheelie() << std::endl; // Motorcycle-specific method
return 0;}Toyota Camry started.Beep beep!Toyota Camry (2020)Yamaha YZF-R3 started.Doing a wheelie!using System;
// Base class (parent/superclass)public class Vehicle{ protected string brand; protected string model; protected int year;
public Vehicle(string brand, string model, int year) { this.brand = brand; this.model = model; this.year = year; }
public string Start() { return $"{brand} {model} started."; }
public string Stop() { return $"{brand} {model} stopped."; }
public string GetInfo() { return $"{brand} {model} ({year})"; }}
// Derived class (child/subclass) - inherits from Vehiclepublic class Car : Vehicle{ private int numDoors;
public Car(string brand, string model, int year, int numDoors) : base(brand, model, year) // Call parent constructor { this.numDoors = numDoors; // Additional attribute }
public string Honk() { return "Beep beep!"; }}
// Another derived classpublic class Motorcycle : Vehicle{ private string bikeType;
public Motorcycle(string brand, string model, int year, string bikeType) : base(brand, model, year) { this.bikeType = bikeType; // Additional attribute }
public string Wheelie() { return "Doing a wheelie!"; }}
// Usageclass Program{ static void Main() { Car car = new Car("Toyota", "Camry", 2020, 4); Console.WriteLine(car.Start()); // Inherited method Console.WriteLine(car.Honk()); // Car-specific method Console.WriteLine(car.GetInfo()); // Inherited method
Motorcycle motorcycle = new Motorcycle("Yamaha", "YZF-R3", 2021, "Sport"); Console.WriteLine(motorcycle.Start()); // Inherited method Console.WriteLine(motorcycle.Wheelie()); // Motorcycle-specific method }}Toyota Camry started.Beep beep!Toyota Camry (2020)Yamaha YZF-R3 started.Doing a wheelie!package main
import "fmt"
type Vehicle struct { Brand string Model string Year int}
func (v *Vehicle) Start() string { return fmt.Sprintf("%s %s started.", v.Brand, v.Model)}
func (v *Vehicle) Stop() string { return fmt.Sprintf("%s %s stopped.", v.Brand, v.Model)}
func (v *Vehicle) GetInfo() string { return fmt.Sprintf("%s %s (%d)", v.Brand, v.Model, v.Year)}
type Car struct { Vehicle NumDoors int}
func (*Car) Honk() string { return "Beep beep!"}
type Motorcycle struct { Vehicle BikeType string}
func (*Motorcycle) Wheelie() string { return "Doing a wheelie!"}
func main() { car := &Car{Vehicle: Vehicle{Brand: "Toyota", Model: "Camry", Year: 2020}, NumDoors: 4} fmt.Println(car.Start()) fmt.Println(car.Honk()) fmt.Println(car.GetInfo())
motorcycle := &Motorcycle{Vehicle: Vehicle{Brand: "Yamaha", Model: "YZF-R3", Year: 2021}, BikeType: "Sport"} fmt.Println(motorcycle.Start()) fmt.Println(motorcycle.Wheelie())}Toyota Camry started.Beep beep!Toyota Camry (2020)Yamaha YZF-R3 started.Doing a wheelie!struct Vehicle { brand: String, model: String, year: u32,}
impl Vehicle { fn start(&self) -> String { format!("{} {} started.", self.brand, self.model) }
fn stop(&self) -> String { format!("{} {} stopped.", self.brand, self.model) }
fn get_info(&self) -> String { format!("{} {} ({})", self.brand, self.model, self.year) }}
struct Car { vehicle: Vehicle, num_doors: u32,}
impl Car { fn honk(&self) -> &'static str { "Beep beep!" }}
struct Motorcycle { vehicle: Vehicle, bike_type: String,}
impl Motorcycle { fn wheelie(&self) -> &'static str { "Doing a wheelie!" }}
fn main() { let car = Car { vehicle: Vehicle { brand: "Toyota".into(), model: "Camry".into(), year: 2020, }, num_doors: 4, }; println!("{}", car.vehicle.start()); println!("{}", car.honk()); println!("{}", car.vehicle.get_info());
let motorcycle = Motorcycle { vehicle: Vehicle { brand: "Yamaha".into(), model: "YZF-R3".into(), year: 2021, }, bike_type: "Sport".into(), }; println!("{}", motorcycle.vehicle.start()); println!("{}", motorcycle.wheelie());}Toyota Camry started.Beep beep!Toyota Camry (2020)Yamaha YZF-R3 started.Doing a wheelie!Method Overriding
Section titled “Method Overriding”Subclasses can override parent methods to provide specialized behavior:
class Vehicle: def __init__(self, brand: str, model: str, year: int): self.brand = brand self.model = model self.year = year
def start(self): return f"{self.brand} {self.model} started."
def fuel_type(self): return "Unknown fuel type"
class Car(Vehicle): def start(self): """Override parent method with specialized behavior""" return f"{self.brand} {self.model} car started with a roar!"
def fuel_type(self): """Override to specify fuel type""" return "Gasoline or Electric"
class ElectricCar(Car): def start(self): """Further override for electric cars""" return f"{self.brand} {self.model} silently started (electric motor)"
def fuel_type(self): """Override to specify electric""" return "Electric"
car = Car("Toyota", "Camry", 2020)print(car.start()) # "Toyota Camry car started with a roar!"print(car.fuel_type()) # "Gasoline or Electric"
electric_car = ElectricCar("Tesla", "Model 3", 2023)print(electric_car.start()) # "Tesla Model 3 silently started (electric motor)"print(electric_car.fuel_type()) # "Electric"public class Vehicle { protected String brand; protected String model; protected int year;
public Vehicle(String brand, String model, int year) { this.brand = brand; this.model = model; this.year = year; }
public String start() { return brand + " " + model + " started."; }
public String fuelType() { return "Unknown fuel type"; }}
public class Car extends Vehicle { public Car(String brand, String model, int year) { super(brand, model, year); }
@Override public String start() { // Override parent method with specialized behavior return brand + " " + model + " car started with a roar!"; }
@Override public String fuelType() { // Override to specify fuel type return "Gasoline or Electric"; }}
public class ElectricCar extends Car { public ElectricCar(String brand, String model, int year) { super(brand, model, year); }
@Override public String start() { // Further override for electric cars return brand + " " + model + " silently started (electric motor)"; }
@Override public String fuelType() { // Override to specify electric return "Electric"; }}
// Usagepublic class Main { public static void main(String[] args) { Car car = new Car("Toyota", "Camry", 2020); System.out.println(car.start()); // "Toyota Camry car started with a roar!" System.out.println(car.fuelType()); // "Gasoline or Electric"
ElectricCar electricCar = new ElectricCar("Tesla", "Model 3", 2023); System.out.println(electricCar.start()); // "Tesla Model 3 silently started (electric motor)" System.out.println(electricCar.fuelType()); // "Electric" }}class Vehicle { protected brand: string; protected model: string; protected year: number;
constructor(brand: string, model: string, year: number) { this.brand = brand; this.model = model; this.year = year; }
start(): string { return `${this.brand} ${this.model} started.`; }
fuelType(): string { return "Unknown fuel type"; }}
class Car extends Vehicle { start(): string { // Override parent method with specialized behavior return `${this.brand} ${this.model} car started with a roar!`; }
fuelType(): string { // Override to specify fuel type return "Gasoline or Electric"; }}
class ElectricCar extends Car { start(): string { // Further override for electric cars return `${this.brand} ${this.model} silently started (electric motor)`; }
fuelType(): string { // Override to specify electric return "Electric"; }}
const car = new Car("Toyota", "Camry", 2020);console.log(car.start()); // "Toyota Camry car started with a roar!"console.log(car.fuelType()); // "Gasoline or Electric"
const electricCar = new ElectricCar("Tesla", "Model 3", 2023);console.log(electricCar.start()); // "Tesla Model 3 silently started (electric motor)"console.log(electricCar.fuelType()); // "Electric"Toyota Camry car started with a roar!Gasoline or ElectricTesla Model 3 silently started (electric motor)Electric#include <iostream>#include <string>
class Vehicle {protected: std::string brand; std::string model; int year;
public: Vehicle(const std::string& brand, const std::string& model, int year) : brand(brand), model(model), year(year) {}
virtual std::string start() const { return brand + " " + model + " started."; }
virtual std::string fuelType() const { return "Unknown fuel type"; }
virtual ~Vehicle() = default;};
class Car : public Vehicle {public: Car(const std::string& brand, const std::string& model, int year) : Vehicle(brand, model, year) {}
std::string start() const override { // Override parent method with specialized behavior return brand + " " + model + " car started with a roar!"; }
std::string fuelType() const override { // Override to specify fuel type return "Gasoline or Electric"; }};
class ElectricCar : public Car {public: ElectricCar(const std::string& brand, const std::string& model, int year) : Car(brand, model, year) {}
std::string start() const override { // Further override for electric cars return brand + " " + model + " silently started (electric motor)"; }
std::string fuelType() const override { // Override to specify electric return "Electric"; }};
int main() { Car car("Toyota", "Camry", 2020); std::cout << car.start() << std::endl; // "Toyota Camry car started with a roar!" std::cout << car.fuelType() << std::endl; // "Gasoline or Electric"
ElectricCar electricCar("Tesla", "Model 3", 2023); std::cout << electricCar.start() << std::endl; // "Tesla Model 3 silently started (electric motor)" std::cout << electricCar.fuelType() << std::endl; // "Electric"
return 0;}Toyota Camry car started with a roar!Gasoline or ElectricTesla Model 3 silently started (electric motor)Electricusing System;
public class Vehicle{ protected string brand; protected string model; protected int year;
public Vehicle(string brand, string model, int year) { this.brand = brand; this.model = model; this.year = year; }
public virtual string Start() { return $"{brand} {model} started."; }
public virtual string FuelType() { return "Unknown fuel type"; }}
public class Car : Vehicle{ public Car(string brand, string model, int year) : base(brand, model, year) {}
public override string Start() { // Override parent method with specialized behavior return $"{brand} {model} car started with a roar!"; }
public override string FuelType() { // Override to specify fuel type return "Gasoline or Electric"; }}
public class ElectricCar : Car{ public ElectricCar(string brand, string model, int year) : base(brand, model, year) {}
public override string Start() { // Further override for electric cars return $"{brand} {model} silently started (electric motor)"; }
public override string FuelType() { // Override to specify electric return "Electric"; }}
class Program{ static void Main() { Car car = new Car("Toyota", "Camry", 2020); Console.WriteLine(car.Start()); // "Toyota Camry car started with a roar!" Console.WriteLine(car.FuelType()); // "Gasoline or Electric"
ElectricCar electricCar = new ElectricCar("Tesla", "Model 3", 2023); Console.WriteLine(electricCar.Start()); // "Tesla Model 3 silently started (electric motor)" Console.WriteLine(electricCar.FuelType()); // "Electric" }}Toyota Camry car started with a roar!Gasoline or ElectricTesla Model 3 silently started (electric motor)Electricpackage main
import "fmt"
type Vehicle struct { Brand string Model string Year int}
func (v *Vehicle) Start() string { return fmt.Sprintf("%s %s started.", v.Brand, v.Model)}
func (v *Vehicle) FuelType() string { return "Unknown fuel type"}
type Car struct { Vehicle}
func (c *Car) Start() string { return fmt.Sprintf("%s %s car started with a roar!", c.Brand, c.Model)}
func (*Car) FuelType() string { return "Gasoline or Electric"}
type ElectricCar struct { Car}
func (e *ElectricCar) Start() string { return fmt.Sprintf("%s %s silently started (electric motor)", e.Brand, e.Model)}
func (*ElectricCar) FuelType() string { return "Electric"}
func main() { car := &Car{Vehicle: Vehicle{Brand: "Toyota", Model: "Camry", Year: 2020}} fmt.Println(car.Start()) fmt.Println(car.FuelType())
electric := &ElectricCar{Car: Car{Vehicle: Vehicle{Brand: "Tesla", Model: "Model 3", Year: 2023}}} fmt.Println(electric.Start()) fmt.Println(electric.FuelType())}Toyota Camry car started with a roar!Gasoline or ElectricTesla Model 3 silently started (electric motor)Electricstruct Vehicle { brand: String, model: String, year: u32,}
impl Vehicle { fn start(&self) -> String { format!("{} {} started.", self.brand, self.model) }
fn fuel_type(&self) -> &'static str { "Unknown fuel type" }}
struct Car { vehicle: Vehicle,}
impl Car { fn start(&self) -> String { format!("{} {} car started with a roar!", self.vehicle.brand, self.vehicle.model) }
fn fuel_type(&self) -> &'static str { "Gasoline or Electric" }}
struct ElectricCar { car: Car,}
impl ElectricCar { fn start(&self) -> String { format!( "{} {} silently started (electric motor)", self.car.vehicle.brand, self.car.vehicle.model ) }
fn fuel_type(&self) -> &'static str { "Electric" }}
fn main() { let car = Car { vehicle: Vehicle { brand: "Toyota".into(), model: "Camry".into(), year: 2020, }, }; println!("{}", car.start()); println!("{}", car.fuel_type());
let electric = ElectricCar { car: Car { vehicle: Vehicle { brand: "Tesla".into(), model: "Model 3".into(), year: 2023, }, }, }; println!("{}", electric.start()); println!("{}", electric.fuel_type());}Toyota Camry car started with a roar!Gasoline or ElectricTesla Model 3 silently started (electric motor)ElectricUsing super()
Section titled “Using super()”The super() function/keyword allows you to call methods from the parent class:
class Employee: def __init__(self, name: str, employee_id: int): self.name = name self.employee_id = employee_id
def get_info(self): return f"Employee: {self.name} (ID: {self.employee_id})"
class Manager(Employee): def __init__(self, name: str, employee_id: int, department: str): super().__init__(name, employee_id) # Call parent __init__ self.department = department
def get_info(self): """Extend parent method using super()""" base_info = super().get_info() # Call parent method return f"{base_info}, Department: {self.department}"
class Director(Manager): def __init__(self, name: str, employee_id: int, department: str, budget: float): super().__init__(name, employee_id, department) # Call Manager's __init__ self.budget = budget
def get_info(self): """Further extend using super()""" manager_info = super().get_info() # Call Manager's get_info return f"{manager_info}, Budget: ${self.budget:,.2f}"
manager = Manager("Alice", 101, "Engineering")print(manager.get_info())# "Employee: Alice (ID: 101), Department: Engineering"
director = Director("Bob", 102, "Engineering", 1000000.0)print(director.get_info())# "Employee: Bob (ID: 102), Department: Engineering, Budget: $1,000,000.00"public class Employee { protected String name; protected int employeeId;
public Employee(String name, int employeeId) { this.name = name; this.employeeId = employeeId; }
public String getInfo() { return "Employee: " + name + " (ID: " + employeeId + ")"; }}
public class Manager extends Employee { private String department;
public Manager(String name, int employeeId, String department) { super(name, employeeId); // Call parent constructor this.department = department; }
@Override public String getInfo() { // Extend parent method using super String baseInfo = super.getInfo(); // Call parent method return baseInfo + ", Department: " + department; }}
public class Director extends Manager { private double budget;
public Director(String name, int employeeId, String department, double budget) { super(name, employeeId, department); // Call Manager's constructor this.budget = budget; }
@Override public String getInfo() { // Further extend using super String managerInfo = super.getInfo(); // Call Manager's getInfo return managerInfo + ", Budget: $" + String.format("%,.2f", budget); }}
// Usagepublic class Main { public static void main(String[] args) { Manager manager = new Manager("Alice", 101, "Engineering"); System.out.println(manager.getInfo()); // "Employee: Alice (ID: 101), Department: Engineering"
Director director = new Director("Bob", 102, "Engineering", 1000000.0); System.out.println(director.getInfo()); // "Employee: Bob (ID: 102), Department: Engineering, Budget: $1,000,000.00" }}class Employee { protected name: string; protected employeeId: number;
constructor(name: string, employeeId: number) { this.name = name; this.employeeId = employeeId; }
getInfo(): string { return `Employee: ${this.name} (ID: ${this.employeeId})`; }}
class Manager extends Employee { private department: string;
constructor(name: string, employeeId: number, department: string) { super(name, employeeId); // Call parent constructor this.department = department; }
getInfo(): string { // Extend parent method using super const baseInfo = super.getInfo(); // Call parent method return `${baseInfo}, Department: ${this.department}`; }}
class Director extends Manager { private budget: number;
constructor(name: string, employeeId: number, department: string, budget: number) { super(name, employeeId, department); // Call Manager's constructor this.budget = budget; }
getInfo(): string { // Further extend using super const managerInfo = super.getInfo(); // Call Manager's getInfo return `${managerInfo}, Budget: $${this.budget.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`; }}
const manager = new Manager("Alice", 101, "Engineering");console.log(manager.getInfo());// "Employee: Alice (ID: 101), Department: Engineering"
const director = new Director("Bob", 102, "Engineering", 1000000.0);console.log(director.getInfo());// "Employee: Bob (ID: 102), Department: Engineering, Budget: $1,000,000.00"Employee: Alice (ID: 101), Department: EngineeringEmployee: Bob (ID: 102), Department: Engineering, Budget: $1,000,000.00#include <iostream>#include <string>#include <iomanip>#include <sstream>
class Employee {protected: std::string name; int employeeId;
public: Employee(const std::string& name, int employeeId) : name(name), employeeId(employeeId) {}
virtual std::string getInfo() const { return "Employee: " + name + " (ID: " + std::to_string(employeeId) + ")"; }
virtual ~Employee() = default;};
class Manager : public Employee {private: std::string department;
public: Manager(const std::string& name, int employeeId, const std::string& department) : Employee(name, employeeId), department(department) {}
std::string getInfo() const override { // Extend parent method using base class call std::string baseInfo = Employee::getInfo(); // Call parent method return baseInfo + ", Department: " + department; }};
class Director : public Manager {private: double budget;
public: Director(const std::string& name, int employeeId, const std::string& department, double budget) : Manager(name, employeeId, department), budget(budget) {}
std::string getInfo() const override { // Further extend using base class call std::string managerInfo = Manager::getInfo(); // Call Manager's getInfo std::ostringstream oss; oss << std::fixed << std::setprecision(2) << budget; return managerInfo + ", Budget: $" + oss.str(); }};
int main() { Manager manager("Alice", 101, "Engineering"); std::cout << manager.getInfo() << std::endl; // "Employee: Alice (ID: 101), Department: Engineering"
Director director("Bob", 102, "Engineering", 1000000.0); std::cout << director.getInfo() << std::endl; // "Employee: Bob (ID: 102), Department: Engineering, Budget: $1000000.00"
return 0;}Employee: Alice (ID: 101), Department: EngineeringEmployee: Bob (ID: 102), Department: Engineering, Budget: $1000000.00using System;
public class Employee{ protected string name; protected int employeeId;
public Employee(string name, int employeeId) { this.name = name; this.employeeId = employeeId; }
public virtual string GetInfo() { return $"Employee: {name} (ID: {employeeId})"; }}
public class Manager : Employee{ private string department;
public Manager(string name, int employeeId, string department) : base(name, employeeId) // Call parent constructor { this.department = department; }
public override string GetInfo() { // Extend parent method using base string baseInfo = base.GetInfo(); // Call parent method return $"{baseInfo}, Department: {department}"; }}
public class Director : Manager{ private double budget;
public Director(string name, int employeeId, string department, double budget) : base(name, employeeId, department) // Call Manager's constructor { this.budget = budget; }
public override string GetInfo() { // Further extend using base string managerInfo = base.GetInfo(); // Call Manager's GetInfo return $"{managerInfo}, Budget: ${budget:N2}"; }}
class Program{ static void Main() { Manager manager = new Manager("Alice", 101, "Engineering"); Console.WriteLine(manager.GetInfo()); // "Employee: Alice (ID: 101), Department: Engineering"
Director director = new Director("Bob", 102, "Engineering", 1000000.0); Console.WriteLine(director.GetInfo()); // "Employee: Bob (ID: 102), Department: Engineering, Budget: $1,000,000.00" }}Employee: Alice (ID: 101), Department: EngineeringEmployee: Bob (ID: 102), Department: Engineering, Budget: $1,000,000.00package main
import "fmt"
type Employee struct { Name string EmployeeID int}
func (e *Employee) GetInfo() string { return fmt.Sprintf("Employee: %s (ID: %d)", e.Name, e.EmployeeID)}
type Manager struct { Employee Department string}
func (m *Manager) GetInfo() string { return fmt.Sprintf("%s, Department: %s", m.Employee.GetInfo(), m.Department)}
type Director struct { Manager Budget float64}
func (d *Director) GetInfo() string { return fmt.Sprintf("%s, Budget: $%.2f", d.Manager.GetInfo(), d.Budget)}
func main() { manager := &Manager{Employee: Employee{Name: "Alice", EmployeeID: 101}, Department: "Engineering"} fmt.Println(manager.GetInfo())
director := &Director{Manager: Manager{Employee: Employee{Name: "Bob", EmployeeID: 102}, Department: "Engineering"}, Budget: 1000000.0} fmt.Println(director.GetInfo())}Employee: Alice (ID: 101), Department: EngineeringEmployee: Bob (ID: 102), Department: Engineering, Budget: $1000000.00struct Employee { name: String, employee_id: u32,}
impl Employee { fn get_info(&self) -> String { format!("Employee: {} (ID: {})", self.name, self.employee_id) }}
struct Manager { employee: Employee, department: String,}
impl Manager { fn get_info(&self) -> String { format!("{}, Department: {}", self.employee.get_info(), self.department) }}
struct Director { manager: Manager, budget: f64,}
impl Director { fn get_info(&self) -> String { format!("{}, Budget: ${:.2}", self.manager.get_info(), self.budget) }}
fn main() { let manager = Manager { employee: Employee { name: "Alice".into(), employee_id: 101, }, department: "Engineering".into(), }; println!("{}", manager.get_info());
let director = Director { manager: Manager { employee: Employee { name: "Bob".into(), employee_id: 102, }, department: "Engineering".into(), }, budget: 1_000_000.0, }; println!("{}", director.get_info());}Employee: Alice (ID: 101), Department: EngineeringEmployee: Bob (ID: 102), Department: Engineering, Budget: $1000000.00Real-World Example: E-commerce System
Section titled “Real-World Example: E-commerce System”class Product: """Base class for all products""" def __init__(self, name: str, price: float, sku: str): self.name = name self.price = price self.sku = sku
def calculate_shipping(self, weight: float) -> float: """Base shipping calculation""" return weight * 2.5 # $2.5 per kg
def get_info(self) -> str: return f"{self.name} - ${self.price:.2f} (SKU: {self.sku})"
class DigitalProduct(Product): """Digital products - no shipping""" def __init__(self, name: str, price: float, sku: str, download_size: float): super().__init__(name, price, sku) self.download_size = download_size # in MB
def calculate_shipping(self, weight: float) -> float: """Override - digital products have no shipping cost""" return 0.0
def get_info(self) -> str: base_info = super().get_info() return f"{base_info} - Digital Download ({self.download_size} MB)"
class PhysicalProduct(Product): """Physical products with weight""" def __init__(self, name: str, price: float, sku: str, weight: float): super().__init__(name, price, sku) self.weight = weight # in kg
def calculate_shipping(self, weight: float = None) -> float: """Override - use product's own weight""" actual_weight = weight if weight else self.weight return super().calculate_shipping(actual_weight)
def get_info(self) -> str: base_info = super().get_info() return f"{base_info} - Weight: {self.weight} kg"
class FragileProduct(PhysicalProduct): """Fragile products need special handling""" def __init__(self, name: str, price: float, sku: str, weight: float): super().__init__(name, price, sku, weight)
def calculate_shipping(self, weight: float = None) -> float: """Override - add handling fee for fragile items""" base_shipping = super().calculate_shipping(weight) handling_fee = 10.0 # Additional $10 for fragile items return base_shipping + handling_fee
def get_info(self) -> str: base_info = super().get_info() return f"{base_info} - FRAGILE"
# Usageebook = DigitalProduct("Python Guide", 29.99, "DIG-001", 5.2)print(ebook.get_info())print(f"Shipping: ${ebook.calculate_shipping(0):.2f}")
book = PhysicalProduct("Python Book", 39.99, "PHY-001", 0.5)print(book.get_info())print(f"Shipping: ${book.calculate_shipping():.2f}")
vase = FragileProduct("Ceramic Vase", 49.99, "FRG-001", 1.2)print(vase.get_info())print(f"Shipping: ${vase.calculate_shipping():.2f}")// Base class for all productspublic class Product { protected String name; protected double price; protected String sku;
public Product(String name, double price, String sku) { this.name = name; this.price = price; this.sku = sku; }
// Base shipping calculation public double calculateShipping(double weight) { return weight * 2.5; // $2.5 per kg }
public String getInfo() { return String.format("%s - $%.2f (SKU: %s)", name, price, sku); }}
// Digital products - no shippingpublic class DigitalProduct extends Product { private double downloadSize; // in MB
public DigitalProduct(String name, double price, String sku, double downloadSize) { super(name, price, sku); this.downloadSize = downloadSize; }
@Override public double calculateShipping(double weight) { // Override - digital products have no shipping cost return 0.0; }
@Override public String getInfo() { String baseInfo = super.getInfo(); return baseInfo + " - Digital Download (" + downloadSize + " MB)"; }}
// Physical products with weightpublic class PhysicalProduct extends Product { private double weight; // in kg
public PhysicalProduct(String name, double price, String sku, double weight) { super(name, price, sku); this.weight = weight; }
public double calculateShipping() { // Override - use product's own weight return calculateShipping(weight); }
@Override public double calculateShipping(double weight) { // Use provided weight or product's own weight double actualWeight = weight > 0 ? weight : this.weight; return super.calculateShipping(actualWeight); }
@Override public String getInfo() { String baseInfo = super.getInfo(); return baseInfo + " - Weight: " + weight + " kg"; }}
// Fragile products need special handlingpublic class FragileProduct extends PhysicalProduct { public FragileProduct(String name, double price, String sku, double weight) { super(name, price, sku, weight); }
@Override public double calculateShipping(double weight) { // Override - add handling fee for fragile items double baseShipping = super.calculateShipping(weight); double handlingFee = 10.0; // Additional $10 for fragile items return baseShipping + handlingFee; }
@Override public String getInfo() { String baseInfo = super.getInfo(); return baseInfo + " - FRAGILE"; }}
// Usagepublic class Main { public static void main(String[] args) { DigitalProduct ebook = new DigitalProduct("Python Guide", 29.99, "DIG-001", 5.2); System.out.println(ebook.getInfo()); System.out.printf("Shipping: $%.2f%n", ebook.calculateShipping(0));
PhysicalProduct book = new PhysicalProduct("Python Book", 39.99, "PHY-001", 0.5); System.out.println(book.getInfo()); System.out.printf("Shipping: $%.2f%n", book.calculateShipping());
FragileProduct vase = new FragileProduct("Ceramic Vase", 49.99, "FRG-001", 1.2); System.out.println(vase.getInfo()); System.out.printf("Shipping: $%.2f%n", vase.calculateShipping()); }}// Base class for all productsclass Product { protected name: string; protected price: number; protected sku: string;
constructor(name: string, price: number, sku: string) { this.name = name; this.price = price; this.sku = sku; }
calculateShipping(weight: number): number { // Base shipping calculation return weight * 2.5; // $2.5 per kg }
getInfo(): string { return `${this.name} - $${this.price.toFixed(2)} (SKU: ${this.sku})`; }}
// Digital products - no shippingclass DigitalProduct extends Product { private downloadSize: number; // in MB
constructor(name: string, price: number, sku: string, downloadSize: number) { super(name, price, sku); this.downloadSize = downloadSize; }
calculateShipping(weight: number): number { // Override - digital products have no shipping cost return 0.0; }
getInfo(): string { const baseInfo = super.getInfo(); return `${baseInfo} - Digital Download (${this.downloadSize} MB)`; }}
// Physical products with weightclass PhysicalProduct extends Product { protected weight: number; // in kg
constructor(name: string, price: number, sku: string, weight: number) { super(name, price, sku); this.weight = weight; }
calculateShipping(weight?: number): number { // Override - use product's own weight const actualWeight = weight !== undefined ? weight : this.weight; return super.calculateShipping(actualWeight); }
getInfo(): string { const baseInfo = super.getInfo(); return `${baseInfo} - Weight: ${this.weight} kg`; }}
// Fragile products need special handlingclass FragileProduct extends PhysicalProduct { calculateShipping(weight?: number): number { // Override - add handling fee for fragile items const baseShipping = super.calculateShipping(weight); const handlingFee = 10.0; // Additional $10 for fragile items return baseShipping + handlingFee; }
getInfo(): string { const baseInfo = super.getInfo(); return `${baseInfo} - FRAGILE`; }}
// Usageconst ebook = new DigitalProduct("Python Guide", 29.99, "DIG-001", 5.2);console.log(ebook.getInfo());console.log(`Shipping: $${ebook.calculateShipping(0).toFixed(2)}`);
const book = new PhysicalProduct("Python Book", 39.99, "PHY-001", 0.5);console.log(book.getInfo());console.log(`Shipping: $${book.calculateShipping().toFixed(2)}`);
const vase = new FragileProduct("Ceramic Vase", 49.99, "FRG-001", 1.2);console.log(vase.getInfo());console.log(`Shipping: $${vase.calculateShipping().toFixed(2)}`);Python Guide - $29.99 (SKU: DIG-001) - Digital Download (5.2 MB)Shipping: $0.00Python Book - $39.99 (SKU: PHY-001) - Weight: 0.5 kgShipping: $1.25Ceramic Vase - $49.99 (SKU: FRG-001) - Weight: 1.2 kg - FRAGILEShipping: $13.00#include <iostream>#include <string>#include <iomanip>
// Base class for all productsclass Product {protected: std::string name; double price; std::string sku;
public: Product(const std::string& name, double price, const std::string& sku) : name(name), price(price), sku(sku) {}
virtual double calculateShipping(double weight) const { return weight * 2.5; // $2.5 per kg }
virtual std::string getInfo() const { return name + " - $" + std::to_string(price).substr(0, std::to_string(price).find('.') + 3) + " (SKU: " + sku + ")"; }
virtual ~Product() = default;};
// Digital products - no shippingclass DigitalProduct : public Product {private: double downloadSize; // in MB
public: DigitalProduct(const std::string& name, double price, const std::string& sku, double downloadSize) : Product(name, price, sku), downloadSize(downloadSize) {}
double calculateShipping(double weight) const override { return 0.0; // Digital products have no shipping cost }
std::string getInfo() const override { return Product::getInfo() + " - Digital Download (" + std::to_string(downloadSize) + " MB)"; }};
// Physical products with weightclass PhysicalProduct : public Product {protected: double weight; // in kg
public: PhysicalProduct(const std::string& name, double price, const std::string& sku, double weight) : Product(name, price, sku), weight(weight) {}
double calculateShipping(double weight = -1) const { double actualWeight = (weight >= 0) ? weight : this->weight; return Product::calculateShipping(actualWeight); }
std::string getInfo() const override { return Product::getInfo() + " - Weight: " + std::to_string(weight) + " kg"; }};
// Fragile products need special handlingclass FragileProduct : public PhysicalProduct {public: FragileProduct(const std::string& name, double price, const std::string& sku, double weight) : PhysicalProduct(name, price, sku, weight) {}
double calculateShipping(double weight = -1) const { double baseShipping = PhysicalProduct::calculateShipping(weight); double handlingFee = 10.0; // Additional $10 for fragile items return baseShipping + handlingFee; }
std::string getInfo() const override { return PhysicalProduct::getInfo() + " - FRAGILE"; }};
int main() { DigitalProduct ebook("Python Guide", 29.99, "DIG-001", 5.2); std::cout << ebook.getInfo() << std::endl; std::cout << std::fixed << std::setprecision(2); std::cout << "Shipping: $" << ebook.calculateShipping(0) << std::endl;
PhysicalProduct book("Python Book", 39.99, "PHY-001", 0.5); std::cout << book.getInfo() << std::endl; std::cout << "Shipping: $" << book.calculateShipping() << std::endl;
FragileProduct vase("Ceramic Vase", 49.99, "FRG-001", 1.2); std::cout << vase.getInfo() << std::endl; std::cout << "Shipping: $" << vase.calculateShipping() << std::endl;
return 0;}Python Guide - $29.99 (SKU: DIG-001) - Digital Download (5.2 MB)Shipping: $0.00Python Book - $39.99 (SKU: PHY-001) - Weight: 0.5 kgShipping: $1.25Ceramic Vase - $49.99 (SKU: FRG-001) - Weight: 1.2 kg - FRAGILEShipping: $13.00using System;
// Base class for all productspublic class Product{ protected string name; protected double price; protected string sku;
public Product(string name, double price, string sku) { this.name = name; this.price = price; this.sku = sku; }
public virtual double CalculateShipping(double weight) { return weight * 2.5; // $2.5 per kg }
public virtual string GetInfo() { return $"{name} - ${price:F2} (SKU: {sku})"; }}
// Digital products - no shippingpublic class DigitalProduct : Product{ private double downloadSize; // in MB
public DigitalProduct(string name, double price, string sku, double downloadSize) : base(name, price, sku) { this.downloadSize = downloadSize; }
public override double CalculateShipping(double weight) { return 0.0; // Digital products have no shipping cost }
public override string GetInfo() { return $"{base.GetInfo()} - Digital Download ({downloadSize} MB)"; }}
// Physical products with weightpublic class PhysicalProduct : Product{ protected double weight; // in kg
public PhysicalProduct(string name, double price, string sku, double weight) : base(name, price, sku) { this.weight = weight; }
public virtual double CalculateShipping() { return CalculateShipping(weight); }
public override double CalculateShipping(double weight) { double actualWeight = weight > 0 ? weight : this.weight; return base.CalculateShipping(actualWeight); }
public override string GetInfo() { return $"{base.GetInfo()} - Weight: {weight} kg"; }}
// Fragile products need special handlingpublic class FragileProduct : PhysicalProduct{ public FragileProduct(string name, double price, string sku, double weight) : base(name, price, sku, weight) {}
public override double CalculateShipping(double weight = 0) { double baseShipping = base.CalculateShipping(weight > 0 ? weight : this.weight); double handlingFee = 10.0; // Additional $10 for fragile items return baseShipping + handlingFee; }
public override string GetInfo() { return $"{base.GetInfo()} - FRAGILE"; }}
class Program{ static void Main() { DigitalProduct ebook = new DigitalProduct("Python Guide", 29.99, "DIG-001", 5.2); Console.WriteLine(ebook.GetInfo()); Console.WriteLine($"Shipping: ${ebook.CalculateShipping(0):F2}");
PhysicalProduct book = new PhysicalProduct("Python Book", 39.99, "PHY-001", 0.5); Console.WriteLine(book.GetInfo()); Console.WriteLine($"Shipping: ${book.CalculateShipping():F2}");
FragileProduct vase = new FragileProduct("Ceramic Vase", 49.99, "FRG-001", 1.2); Console.WriteLine(vase.GetInfo()); Console.WriteLine($"Shipping: ${vase.CalculateShipping():F2}"); }}Python Guide - $29.99 (SKU: DIG-001) - Digital Download (5.2 MB)Shipping: $0.00Python Book - $39.99 (SKU: PHY-001) - Weight: 0.5 kgShipping: $1.25Ceramic Vase - $49.99 (SKU: FRG-001) - Weight: 1.2 kg - FRAGILEShipping: $13.00package main
import "fmt"
type Product struct { Name string Price float64 SKU string}
func (p *Product) CalculateShipping(weight float64) float64 { return weight * 2.5}
func (p *Product) GetInfo() string { return fmt.Sprintf("%s - $%.2f (SKU: %s)", p.Name, p.Price, p.SKU)}
type DigitalProduct struct { Product DownloadSize float64}
func (d *DigitalProduct) CalculateShipping(weight float64) float64 { return 0}
func (d *DigitalProduct) GetInfo() string { return fmt.Sprintf("%s - Digital Download (%.1f MB)", d.Product.GetInfo(), d.DownloadSize)}
type PhysicalProduct struct { Product Weight float64}
func (p *PhysicalProduct) CalculateShipping(weight float64) float64 { w := weight if w <= 0 { w = p.Weight } return p.Product.CalculateShipping(w)}
func (p *PhysicalProduct) GetInfo() string { return fmt.Sprintf("%s - Weight: %.1f kg", p.Product.GetInfo(), p.Weight)}
type FragileProduct struct { PhysicalProduct}
func (f *FragileProduct) CalculateShipping(weight float64) float64 { w := weight if w <= 0 { w = f.Weight } base := f.PhysicalProduct.Product.CalculateShipping(w) return base + 10.0}
func (f *FragileProduct) GetInfo() string { return fmt.Sprintf("%s - FRAGILE", f.PhysicalProduct.GetInfo())}
func main() { ebook := &DigitalProduct{Product: Product{Name: "Python Guide", Price: 29.99, SKU: "DIG-001"}, DownloadSize: 5.2} fmt.Println(ebook.GetInfo()) fmt.Printf("Shipping: $%.2f\n", ebook.CalculateShipping(0))
book := &PhysicalProduct{Product: Product{Name: "Python Book", Price: 39.99, SKU: "PHY-001"}, Weight: 0.5} fmt.Println(book.GetInfo()) fmt.Printf("Shipping: $%.2f\n", book.CalculateShipping(0))
vase := &FragileProduct{PhysicalProduct: PhysicalProduct{Product: Product{Name: "Ceramic Vase", Price: 49.99, SKU: "FRG-001"}, Weight: 1.2}} fmt.Println(vase.GetInfo()) fmt.Printf("Shipping: $%.2f\n", vase.CalculateShipping(0))}Python Guide - $29.99 (SKU: DIG-001) - Digital Download (5.2 MB)Shipping: $0.00Python Book - $39.99 (SKU: PHY-001) - Weight: 0.5 kgShipping: $1.25Ceramic Vase - $49.99 (SKU: FRG-001) - Weight: 1.2 kg - FRAGILEShipping: $13.00struct Product { name: String, price: f64, sku: String,}
impl Product { fn calculate_shipping(&self, weight: f64) -> f64 { weight * 2.5 }
fn get_info(&self) -> String { format!("{} - ${:.2} (SKU: {})", self.name, self.price, self.sku) }}
struct DigitalProduct { product: Product, download_size: f64,}
impl DigitalProduct { fn calculate_shipping(&self, _weight: f64) -> f64 { 0.0 }
fn get_info(&self) -> String { format!( "{} - Digital Download ({:.1} MB)", self.product.get_info(), self.download_size ) }}
struct PhysicalProduct { product: Product, weight: f64,}
impl PhysicalProduct { fn calculate_shipping(&self, weight: f64) -> f64 { let w = if weight <= 0.0 { self.weight } else { weight }; self.product.calculate_shipping(w) }
fn get_info(&self) -> String { format!("{} - Weight: {:.1} kg", self.product.get_info(), self.weight) }}
struct FragileProduct { physical: PhysicalProduct,}
impl FragileProduct { fn calculate_shipping(&self, weight: f64) -> f64 { let w = if weight <= 0.0 { self.physical.weight } else { weight }; self.physical.product.calculate_shipping(w) + 10.0 }
fn get_info(&self) -> String { format!("{} - FRAGILE", self.physical.get_info()) }}
fn main() { let ebook = DigitalProduct { product: Product { name: "Python Guide".into(), price: 29.99, sku: "DIG-001".into(), }, download_size: 5.2, }; println!("{}", ebook.get_info()); println!("Shipping: ${:.2}", ebook.calculate_shipping(0.0));
let book = PhysicalProduct { product: Product { name: "Python Book".into(), price: 39.99, sku: "PHY-001".into(), }, weight: 0.5, }; println!("{}", book.get_info()); println!("Shipping: ${:.2}", book.calculate_shipping(0.0));
let vase = FragileProduct { physical: PhysicalProduct { product: Product { name: "Ceramic Vase".into(), price: 49.99, sku: "FRG-001".into(), }, weight: 1.2, }, }; println!("{}", vase.get_info()); println!("Shipping: ${:.2}", vase.calculate_shipping(0.0));}Python Guide - $29.99 (SKU: DIG-001) - Digital Download (5.2 MB)Shipping: $0.00Python Book - $39.99 (SKU: PHY-001) - Weight: 0.5 kgShipping: $1.25Ceramic Vase - $49.99 (SKU: FRG-001) - Weight: 1.2 kg - FRAGILEShipping: $13.00Multiple Inheritance
Section titled “Multiple Inheritance”class Flyable: def fly(self): return "Flying through the air"
class Swimmable: def swim(self): return "Swimming in water"
class Duck(Flyable, Swimmable): """Duck can both fly and swim""" def __init__(self, name: str): self.name = name
def quack(self): return f"{self.name} says quack!"
duck = Duck("Donald")print(duck.fly()) # From Flyableprint(duck.swim()) # From Swimmableprint(duck.quack()) # Duck's own method// Java uses interfaces for multiple inheritance-like behaviorpublic interface Flyable { default void fly() { System.out.println("Flying through the air"); }}
public interface Swimmable { default void swim() { System.out.println("Swimming in water"); }}
// Duck implements multiple interfaces (similar to multiple inheritance)public class Duck implements Flyable, Swimmable { private String name;
public Duck(String name) { this.name = name; }
public void quack() { System.out.println(name + " says quack!"); }}
// Usagepublic class Main { public static void main(String[] args) { Duck duck = new Duck("Donald"); duck.fly(); // From Flyable interface duck.swim(); // From Swimmable interface duck.quack(); // Duck's own method }}Note: Java 8+ introduced default methods in interfaces, allowing interfaces to provide method implementations. This gives you multiple inheritance-like behavior while avoiding the diamond problem.
// TypeScript uses interfaces for multiple inheritance-like behaviorinterface Flyable { fly(): void;}
interface Swimmable { swim(): void;}
// Duck implements multiple interfacesclass Duck implements Flyable, Swimmable { private name: string;
constructor(name: string) { this.name = name; }
fly(): void { console.log("Flying through the air"); }
swim(): void { console.log("Swimming in water"); }
quack(): void { console.log(`${this.name} says quack!`); }}
// Usageconst duck = new Duck("Donald");duck.fly(); // From Flyable interfaceduck.swim(); // From Swimmable interfaceduck.quack(); // Duck's own methodFlying through the airSwimming in waterDonald says quack!#include <iostream>#include <string>
// C++ supports true multiple inheritanceclass Flyable {public: void fly() const { std::cout << "Flying through the air" << std::endl; }};
class Swimmable {public: void swim() const { std::cout << "Swimming in water" << std::endl; }};
// Duck inherits from both Flyable and Swimmableclass Duck : public Flyable, public Swimmable {private: std::string name;
public: Duck(const std::string& name) : name(name) {}
void quack() const { std::cout << name << " says quack!" << std::endl; }};
int main() { Duck duck("Donald"); duck.fly(); // From Flyable duck.swim(); // From Swimmable duck.quack(); // Duck's own method
return 0;}Flying through the airSwimming in waterDonald says quack!using System;
// C# uses interfaces for multiple inheritance-like behaviorpublic interface IFlyable{ void Fly();}
public interface ISwimmable{ void Swim();}
// Duck implements multiple interfacespublic class Duck : IFlyable, ISwimmable{ private string name;
public Duck(string name) { this.name = name; }
public void Fly() { Console.WriteLine("Flying through the air"); }
public void Swim() { Console.WriteLine("Swimming in water"); }
public void Quack() { Console.WriteLine($"{name} says quack!"); }}
class Program{ static void Main() { Duck duck = new Duck("Donald"); duck.Fly(); // From IFlyable interface duck.Swim(); // From ISwimmable interface duck.Quack(); // Duck's own method }}Flying through the airSwimming in waterDonald says quack!package main
import "fmt"
type Flyable struct{}
func (*Flyable) Fly() { fmt.Println("Flying through the air")}
type Swimmable struct{}
func (*Swimmable) Swim() { fmt.Println("Swimming in water")}
type Duck struct { Flyable Swimmable Name string}
func (d *Duck) Quack() { fmt.Printf("%s says quack!\n", d.Name)}
func main() { duck := &Duck{Name: "Donald"} duck.Fly() duck.Swim() duck.Quack()}Flying through the airSwimming in waterDonald says quack!trait Flyable { fn fly(&self);}
trait Swimmable { fn swim(&self);}
struct Duck { name: String,}
impl Flyable for Duck { fn fly(&self) { println!("Flying through the air"); }}
impl Swimmable for Duck { fn swim(&self) { println!("Swimming in water"); }}
impl Duck { fn quack(&self) { println!("{} says quack!", self.name); }}
fn main() { let duck = Duck { name: "Donald".into(), }; duck.fly(); duck.swim(); duck.quack();}Flying through the airSwimming in waterDonald says quack!Method Resolution Order (MRO)
Section titled “Method Resolution Order (MRO)”When using multiple inheritance, Python uses Method Resolution Order to determine which method to call:
class A: def method(self): return "A"
class B(A): def method(self): return "B"
class C(A): def method(self): return "C"
class D(B, C): pass
d = D()print(d.method()) # "B" - B comes before C in MROprint(D.__mro__) # Shows the method resolution order// Java uses single inheritance, so no MRO complexitypublic class A { public String method() { return "A"; }}
public class B extends A { @Override public String method() { return "B"; }}
// Java doesn't allow: class D extends B, C// Instead, you use interfaces for multiple inheritance-like behavior
public interface Interface1 { default String method() { return "Interface1"; }}
public interface Interface2 { default String method() { return "Interface2"; }}
// If both interfaces have the same method, class must overridepublic class D implements Interface1, Interface2 { @Override public String method() { // Must override to resolve conflict return "D resolves conflict"; }}
// Usagepublic class Main { public static void main(String[] args) { B b = new B(); System.out.println(b.method()); // "B" - simple override
D d = new D(); System.out.println(d.method()); // "D resolves conflict" - must override }}Key Difference: Python’s MRO handles multiple inheritance automatically, while Java requires explicit resolution when interfaces conflict.
// TypeScript uses single inheritance, so no MRO complexityclass A { method(): string { return "A"; }}
class B extends A { method(): string { return "B"; }}
// TypeScript doesn't allow: class D extends B, C// Instead, you use interfaces for multiple inheritance-like behavior
interface Interface1 { method(): string;}
interface Interface2 { method(): string;}
// If both interfaces have the same method signature, class must implementclass D implements Interface1, Interface2 { method(): string { // Must implement to satisfy both interfaces return "D resolves conflict"; }}
// Usageconst b = new B();console.log(b.method()); // "B" - simple override
const d = new D();console.log(d.method()); // "D resolves conflict" - must implementBD resolves conflict#include <iostream>#include <string>
// C++ supports multiple inheritanceclass A {public: virtual std::string method() const { return "A"; } virtual ~A() = default;};
class B : public A {public: std::string method() const override { return "B"; }};
class C : public A {public: std::string method() const override { return "C"; }};
// Multiple inheritance - must specify which method to useclass D : public B, public C {public: std::string method() const override { // Must override to resolve ambiguity return "D resolves conflict (using B: " + B::method() + ")"; }};
int main() { B b; std::cout << b.method() << std::endl; // "B" - simple override
D d; std::cout << d.method() << std::endl; // "D resolves conflict (using B: B)"
return 0;}BD resolves conflict (using B: B)using System;
// C# uses single inheritance, so no MRO complexitypublic class A{ public virtual string Method() { return "A"; }}
public class B : A{ public override string Method() { return "B"; }}
// C# doesn't allow: class D : B, C// Instead, you use interfaces for multiple inheritance-like behavior
public interface IInterface1{ string Method();}
public interface IInterface2{ string Method();}
// If both interfaces have the same method, class must implementpublic class D : IInterface1, IInterface2{ // Implement the method to satisfy both interfaces public string Method() { return "D resolves conflict"; }}
class Program{ static void Main() { B b = new B(); Console.WriteLine(b.Method()); // "B" - simple override
D d = new D(); Console.WriteLine(d.Method()); // "D resolves conflict" - must implement }}BD resolves conflictKey Difference: C# uses single inheritance with interfaces for multiple contracts, avoiding MRO complexity entirely.
package main
import "fmt"
type A struct{}
func (*A) Method() string { return "A" }
type B struct{ A }
func (*B) Method() string { return "B" }
type I1 interface{ Method() string }type I2 interface{ Method() string }
type D struct{}
func (*D) Method() string { return "D resolves conflict" }
var _ I1 = (*D)(nil)var _ I2 = (*D)(nil)
func main() { b := &B{} fmt.Println(b.Method())
d := &D{} fmt.Println(d.Method())}BD resolves conflictKey difference: Go has no class MRO; a struct embeds at most one parent type for promotion. Interface composition still requires an explicit method set on the concrete type.
struct A;
impl A { fn method(&self) -> &'static str { "A" }}
struct B { a: A,}
impl B { fn method(&self) -> &'static str { "B" }}
trait I1 { fn method(&self) -> String;}
trait I2 { fn method(&self) -> String;}
struct D;
impl I1 for D { fn method(&self) -> String { "D resolves conflict".to_string() }}
impl I2 for D { fn method(&self) -> String { "D resolves conflict".to_string() }}
fn main() { let b = B { a: A }; println!("{}", b.method());
let d = D; println!("{}", I1::method(&d));}BD resolves conflictKey difference: Rust has no class MRO; a struct embeds fields or uses traits for shared behavior. Trait composition still requires an explicit method set on the concrete type.
Key Takeaways
Section titled “Key Takeaways”- Inheritance creates an “is-a” relationship between classes
- Subclasses inherit all attributes and methods from parent classes
- Method overriding allows subclasses to provide specialized behavior
super()is used to call parent class methods- Multiple inheritance allows a class to inherit from multiple parents
- MRO determines the order in which methods are resolved in multiple inheritance
- Use inheritance to reuse code and create specialized classes from general ones
Inheritance is powerful for creating class hierarchies where specialized classes extend and customize the behavior of more general classes.