Inheritance
π§ What is Inheritance?
Inheritance is a core object-oriented programming principle that allows one class (called a subclass or child class) to inherit the fields and methods of another class (called a superclass or parent class).
It enables the reuse of code and supports hierarchical classification.
π Real-world Analogy:
Imagine a Vehicle class. A Car, Bike, and Truck are all vehicles β they share common properties like speed, engine, and methods like start()
or stop()
.
Instead of duplicating code in each class, we define these common features once in the Vehicle
class and have Car
, Bike
, and Truck
inherit from it.
π§ Java Syntax Example
// Parent Class
class Vehicle {
int speed = 50;
void start() {
System.out.println("Vehicle is starting...");
}
}
// Child Class
class Car extends Vehicle {
void honk() {
System.out.println("Car horn: Beep beep!");
}
}
// Main Class
public class Main {
public static void main(String[] args) {
Car myCar = new Car();
myCar.start(); // Inherited method
myCar.honk(); // Child method
System.out.println("Speed: " + myCar.speed); // Inherited field
}
}
π― Why Use Inheritance?
Inheritance isn’t just about reusing code β it plays a fundamental role in software architecture.
β Code Reusability
You avoid writing redundant code by placing shared logic in the parent class.
β Extensibility
New classes can be built on existing ones, following the Open/Closed Principle (open for extension, closed for modification).
β Polymorphism
Inheritance allows subclasses to override parent methods, enabling dynamic behavior at runtime.
β Hierarchical Modeling
You can represent real-world relationships in a class hierarchy, which enhances code readability and maintainability.
π₯ Key Rules of Inheritance in Java
Rule | Description |
---|---|
extends keyword | Used to inherit a class |
Single inheritance | Java only supports single class inheritance (one parent) |
Constructors | Not inherited, but super() can call parent constructor |
Private members | Not directly accessible in child classes |
Static members | Inherited but not overridden |
β Common Pitfalls
- Overusing inheritance can lead to rigid and tightly coupled systems.
- Prefer composition over inheritance when βhas-aβ makes more sense than βis-aβ.
π Homework for Students
1. Create a class hierarchy where:
Employee
is the base class with name, id, and a methodwork()
.Manager
extends Employee and adds a methodconductMeeting()
.Developer
extends Employee and adds a methodwriteCode()
.
2. Create objects of both child classes and demonstrate:
- Inherited methods and fields.
- Child-specific behavior.
- Print outputs showing inheritance in action.
Would you like to proceed with Access Modifiers next, or go into Method Overriding inside inheritance (deeper dive)?