Inheritance
Don't reinvent the wheel. Inherit it.
Inheritance
Analogy: biology
Inheritance is like DNA. You inherit features (eyes, hair color) from your parents, but you also add your own unique traits.
In code, a Child Class gets all the code from a Parent Class for free!
The Robot Factory
Why build a robot from scratch every time?
- Start with a Basic Robot (Head, Body, Legs).
- Create a Warrior Robot that extends Basic Robot and adds a Weapon.
- Create a Flying Robot that extends Basic Robot and adds Wings.
Robot Builder (Inheritance)
Select Class
Inheritance Logic:
The Parent Class. Has basic movement and sensors.
The Code
Java Example
Switch language in Navbar
// The Parent Class
class BasicRobot {
void walk() {
System.out.println("Walking...");
}
}
// The Child Class
class WarriorRobot extends BasicRobot {
void attack() {
System.out.println("Attacking with Laser!");
}
}
When you create a WarriorRobot, it can walk() AND attack()!
Advanced Concepts
1. The Diamond Problem
Imagine a child inherits from two parents who both have a method called cook().
- Parent A cooks Pasta.
- Parent B cooks Pizza.
- Child: "Which
cook()do I use?!"
This ambiguity is the Diamond Problem. Many languages (like Java) avoid this by disallowing Multiple Inheritance of classes. C++ allows it but requires careful handling.
2. Constructor Chaining
When you create a Child object, the Parent must be born first!
- Child Constructor calls
super()(Parent Constructor). - This chain goes all the way up to the root ancestor.
Java Example
Switch language in Navbar
class Child extends Parent {
Child() {
super(); // Call Parent's constructor first!
System.out.println("Child Created");
}
}
Up Next
Polymorphism