Inheritance
Inheritance in Object-Oriented Programming
Learn what inheritance is in Object-Oriented Programming, why it is used, how parent and child classes work, different types of inheritance, method overriding, real-world examples, advantages, limitations, and best practices.
Introduction
Inheritance is one of the most important principles of Object-Oriented Programming. It allows one class to acquire the properties and methods of another class. In simple words, inheritance allows a new class to reuse the features of an existing class.
In Object-Oriented Programming, inheritance helps create a relationship between classes. The class that provides properties and methods is called the parent class, base class, or superclass. The class that receives or inherits those features is called the child class, derived class, or subclass.
For example, suppose we have a general class named Vehicle. This class may contain common properties such as brand, model, speed, and fuel level. Now, classes like Car, Bike, and Truck can inherit these common features from Vehicle instead of rewriting the same properties and methods again and again.
Simple Definition of Inheritance
Inheritance is a mechanism in Object-Oriented Programming that allows a class to use the features of another class. It helps create reusable, organized, and hierarchical code.
In simple words:
- Inheritance allows one class to reuse another class.
- It reduces code duplication.
- It creates a parent-child relationship between classes.
- It helps build class hierarchies.
- It supports code reusability and extensibility.
- It allows child classes to add or modify behavior.
Real-World Analogy of Inheritance
To understand inheritance easily, think about family inheritance. A child may inherit certain characteristics from parents, such as surname, eye color, or some family traits. The child may also have unique qualities of their own.
Similarly, in programming, a child class can inherit properties and methods from a parent class, but it can also define its own additional properties and methods.
Inheritance as Family Relationship
A child can inherit common characteristics from a parent, but can also have unique features. In OOP, a child class inherits common features from a parent class and can add its own features.
| Real-World Concept | Programming Concept | Explanation |
|---|---|---|
| Parent | Parent Class / Base Class | Provides common characteristics and behavior. |
| Child | Child Class / Derived Class | Receives common features and adds its own features. |
| Family Traits | Inherited Properties and Methods | Features passed from parent class to child class. |
| Unique Personality | Child-Specific Members | Extra features defined only in the child class. |
Why Do We Need Inheritance?
Inheritance is needed because many classes in a program may have common features. Without inheritance, developers may need to write the same properties and methods repeatedly in multiple classes. This increases code duplication and makes maintenance difficult.
For example, Car, Bike, and Truck are different types of vehicles. They may all have brand, model, speed, start(), stop(), and accelerate() features. Instead of writing these features separately in every class, we can create a common Vehicle class and allow Car, Bike, and Truck to inherit from it.
Without Inheritance
- Same code may be repeated in many classes.
- Maintenance becomes difficult when common logic changes.
- Program structure may become disorganized.
- Relationships between classes may not be clear.
- Code becomes longer and harder to manage.
- Reusability becomes limited.
With Inheritance
- Common code is written once in the parent class.
- Child classes reuse parent class features.
- Code becomes shorter and cleaner.
- Class relationships become easier to understand.
- Maintenance becomes easier.
- New classes can be created by extending existing classes.
Parent Class and Child Class
In inheritance, two important terms are parent class and child class. The parent class contains common features, and the child class inherits those features.
The child class can use inherited properties and methods. It can also add new properties and methods or modify inherited behavior according to its requirement.
| Term | Other Names | Meaning |
|---|---|---|
| Parent Class | Base Class, Superclass | The class whose features are inherited. |
| Child Class | Derived Class, Subclass | The class that inherits features from another class. |
| Inheritance Relationship | Is-A Relationship | A child class is a specialized form of the parent class. |
| Extension | Specialization | Child class adds extra features to inherited features. |
Real-World Example: Vehicle Inheritance
Let us understand inheritance using a vehicle example. A vehicle can be a general class that contains common features. Car, Bike, and Truck can be specialized classes that inherit from Vehicle.
| Parent Class | Child Classes | Common Features Inherited |
|---|---|---|
| Vehicle | Car, Bike, Truck | brand, model, speed, start(), stop(), accelerate() |
// Conceptual inheritance example
Class Vehicle
{
brand
model
speed
start()
{
print "Vehicle started"
}
stop()
{
print "Vehicle stopped"
}
}
Class Car inherits Vehicle
{
numberOfDoors
openTrunk()
{
print "Trunk opened"
}
}
Class Bike inherits Vehicle
{
hasCarrier
kickStart()
{
print "Bike kick started"
}
}
In this conceptual example, Car and Bike inherit common properties and methods from Vehicle. Car also adds its own feature openTrunk(), while Bike adds kickStart().
Basic Syntax Concept of Inheritance
The syntax of inheritance differs from language to language. However, the basic idea is the same: one class extends or inherits another class.
// General conceptual syntax
Class ParentClass
{
// common properties and methods
}
Class ChildClass inherits ParentClass
{
// child-specific properties and methods
}
In many programming languages, keywords such as extends, inherits, or : are used to define inheritance.
Java Example of Inheritance
In Java, inheritance is implemented using the extends keyword. The child class extends the parent class and can use its accessible properties and methods.
class Vehicle {
String brand;
int speed;
void start() {
System.out.println("Vehicle started");
}
void stop() {
System.out.println("Vehicle stopped");
}
void displayVehicleDetails() {
System.out.println("Brand: " + brand);
System.out.println("Speed: " + speed);
}
}
class Car extends Vehicle {
int numberOfDoors;
void openTrunk() {
System.out.println("Car trunk opened");
}
void displayCarDetails() {
displayVehicleDetails();
System.out.println("Number of Doors: " + numberOfDoors);
}
}
public class Main {
public static void main(String[] args) {
Car car1 = new Car();
car1.brand = "Toyota";
car1.speed = 80;
car1.numberOfDoors = 4;
car1.start();
car1.displayCarDetails();
car1.openTrunk();
car1.stop();
}
}
In this example, Vehicle is the parent class and Car is the child class. The Car class inherits brand, speed, start(), stop(), and displayVehicleDetails() from Vehicle. It also adds its own property numberOfDoors and method openTrunk().
JavaScript Example of Inheritance
JavaScript supports class inheritance using the extends keyword. The child class can use the super keyword to call the parent class constructor.
class Vehicle {
constructor(brand, speed) {
this.brand = brand;
this.speed = speed;
}
start() {
console.log("Vehicle started");
}
stop() {
console.log("Vehicle stopped");
}
displayVehicleDetails() {
console.log("Brand: " + this.brand);
console.log("Speed: " + this.speed);
}
}
class Car extends Vehicle {
constructor(brand, speed, numberOfDoors) {
super(brand, speed);
this.numberOfDoors = numberOfDoors;
}
openTrunk() {
console.log("Car trunk opened");
}
displayCarDetails() {
this.displayVehicleDetails();
console.log("Number of Doors: " + this.numberOfDoors);
}
}
const car1 = new Car("Honda", 90, 4);
car1.start();
car1.displayCarDetails();
car1.openTrunk();
car1.stop();
In this JavaScript example, Car extends Vehicle. The super() call sends brand and speed values to the parent class constructor.
The super Keyword
In many object-oriented languages, a keyword like super is used to refer to the parent class. It can be used to call the parent class constructor or parent class methods.
The exact syntax depends on the programming language, but the idea is that the child class can use parent class functionality through a special reference.
class Vehicle {
Vehicle() {
System.out.println("Vehicle constructor called");
}
}
class Car extends Vehicle {
Car() {
super();
System.out.println("Car constructor called");
}
}
In this example, super() calls the parent class constructor from the child class constructor.
Is-A Relationship in Inheritance
Inheritance represents an Is-A relationship. This means the child class should be a specialized version of the parent class.
For example, a Car is a Vehicle, a Dog is an Animal, and a Student is a Person. These are good examples of inheritance because the relationship is natural and logical.
| Parent Class | Child Class | Is-A Statement |
|---|---|---|
| Vehicle | Car | A Car is a Vehicle. |
| Animal | Dog | A Dog is an Animal. |
| Person | Student | A Student is a Person. |
| Employee | Manager | A Manager is an Employee. |
| Shape | Circle | A Circle is a Shape. |
Types of Inheritance
Inheritance can be categorized into several types based on how classes are connected. Not every programming language supports every type of inheritance directly, but understanding these types is important for OOP theory and design.
Single Inheritance
One child class inherits from one parent class
Single inheritance is the simplest type of inheritance. A child class inherits from only one parent class.
Multilevel Inheritance
A class inherits from a class that already inherits from another class
In multilevel inheritance, inheritance happens in a chain. A class can be a child of one class and also a parent of another class.
Hierarchical Inheritance
Multiple child classes inherit from one parent class
In hierarchical inheritance, one parent class is inherited by many child classes.
Multiple Inheritance
One child class inherits from multiple parent classes
In multiple inheritance, a child class inherits from more than one parent class. Some languages support this directly, while others avoid it or support similar behavior through interfaces.
Hybrid Inheritance
Combination of multiple types of inheritance
Hybrid inheritance is a combination of two or more inheritance types. It is more complex and should be used carefully.
Types of Inheritance Comparison
| Type | Structure | Simple Example | Complexity |
|---|---|---|---|
| Single Inheritance | One parent, one child | Car inherits Vehicle | Simple |
| Multilevel Inheritance | Inheritance chain | ElectricCar inherits Car, Car inherits Vehicle | Moderate |
| Hierarchical Inheritance | One parent, multiple children | Car, Bike, Truck inherit Vehicle | Moderate |
| Multiple Inheritance | Multiple parents, one child | SmartDevice inherits Camera and Phone | Complex |
| Hybrid Inheritance | Combination of inheritance types | Mixed class hierarchy | High |
Single Inheritance Example
Single inheritance occurs when one child class inherits from one parent class.
class Animal {
void eat() {
System.out.println("Animal eats food");
}
}
class Dog extends Animal {
void bark() {
System.out.println("Dog barks");
}
}
public class Main {
public static void main(String[] args) {
Dog dog1 = new Dog();
dog1.eat();
dog1.bark();
}
}
In this example, Dog inherits the eat() method from Animal and also has its own bark() method.
Multilevel Inheritance Example
Multilevel inheritance occurs when a class inherits from another child class, forming a chain.
class Vehicle {
void start() {
System.out.println("Vehicle started");
}
}
class Car extends Vehicle {
void drive() {
System.out.println("Car is driving");
}
}
class ElectricCar extends Car {
void chargeBattery() {
System.out.println("Battery is charging");
}
}
public class Main {
public static void main(String[] args) {
ElectricCar tesla = new ElectricCar();
tesla.start();
tesla.drive();
tesla.chargeBattery();
}
}
In this example, ElectricCar inherits from Car, and Car inherits from Vehicle. Therefore, ElectricCar can use methods from both Car and Vehicle.
Hierarchical Inheritance Example
Hierarchical inheritance occurs when multiple child classes inherit from the same parent class.
class Shape {
void draw() {
System.out.println("Drawing a shape");
}
}
class Circle extends Shape {
void calculateCircleArea() {
System.out.println("Calculating circle area");
}
}
class Rectangle extends Shape {
void calculateRectangleArea() {
System.out.println("Calculating rectangle area");
}
}
public class Main {
public static void main(String[] args) {
Circle circle1 = new Circle();
Rectangle rectangle1 = new Rectangle();
circle1.draw();
circle1.calculateCircleArea();
rectangle1.draw();
rectangle1.calculateRectangleArea();
}
}
In this example, both Circle and Rectangle inherit the draw() method from Shape.
Method Overriding in Inheritance
Method overriding occurs when a child class provides its own version of a method that is already defined in the parent class. This allows the child class to customize inherited behavior.
For example, an Animal class may have a makeSound() method. Dog and Cat classes can override this method to produce different sounds.
class Animal {
void makeSound() {
System.out.println("Animal makes a sound");
}
}
class Dog extends Animal {
void makeSound() {
System.out.println("Dog barks");
}
}
class Cat extends Animal {
void makeSound() {
System.out.println("Cat meows");
}
}
public class Main {
public static void main(String[] args) {
Dog dog1 = new Dog();
Cat cat1 = new Cat();
dog1.makeSound();
cat1.makeSound();
}
}
In this example, Dog and Cat override the makeSound() method from Animal and provide their own behavior.
Method Overloading vs Method Overriding
Method overloading and method overriding are different concepts. Overloading means multiple methods with the same name but different parameters. Overriding means redefining a parent class method in a child class.
| Basis | Method Overloading | Method Overriding |
|---|---|---|
| Meaning | Same method name with different parameters. | Child class redefines parent class method. |
| Class Relationship | Can happen in the same class. | Requires inheritance. |
| Purpose | Provides different ways to call a method. | Changes inherited behavior. |
| Example | add(int, int), add(double, double) | Dog overrides makeSound() |
| Parameter List | Must be different. | Usually same method signature. |
Access Modifiers and Inheritance
Access modifiers affect what members of a parent class can be accessed by a child class. The exact rules depend on the programming language, but common modifiers include public, private, and protected.
| Access Modifier | Access in Child Class | Common Use |
|---|---|---|
| public | Usually accessible in child class and outside class. | Methods that should be available publicly. |
| protected | Usually accessible inside child class. | Members intended for inheritance-based access. |
| private | Usually not directly accessible in child class. | Sensitive internal data of parent class. |
Real-World Example: Employee and Manager
In many business applications, Employee can be a parent class and Manager can be a child class. A manager is an employee, but a manager may also have additional responsibilities.
class Employee {
String employeeId;
String name;
double salary;
void displayEmployeeDetails() {
System.out.println("Employee ID: " + employeeId);
System.out.println("Name: " + name);
System.out.println("Salary: " + salary);
}
void work() {
System.out.println(name + " is working");
}
}
class Manager extends Employee {
String department;
void conductMeeting() {
System.out.println(name + " is conducting a meeting for " + department);
}
void displayManagerDetails() {
displayEmployeeDetails();
System.out.println("Department: " + department);
}
}
public class Main {
public static void main(String[] args) {
Manager manager1 = new Manager();
manager1.employeeId = "E101";
manager1.name = "Ayesha";
manager1.salary = 75000;
manager1.department = "IT";
manager1.work();
manager1.displayManagerDetails();
manager1.conductMeeting();
}
}
In this example, Manager inherits employeeId, name, salary, work(), and displayEmployeeDetails() from Employee. Manager also adds department and conductMeeting().
Real-World Example: School Management System
In a school management system, Person can be a parent class. Student and Teacher can inherit from Person because both students and teachers are people with common details such as name, age, and contact number.
| Parent Class | Child Class | Inherited Features | Child-Specific Features |
|---|---|---|---|
| Person | Student | name, age, contactNumber | rollNumber, course, marks |
| Person | Teacher | name, age, contactNumber | teacherId, subject, salary |
class Person {
String name;
int age;
String contactNumber;
void displayBasicDetails() {
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Contact Number: " + contactNumber);
}
}
class Student extends Person {
int rollNumber;
String course;
void displayStudentDetails() {
displayBasicDetails();
System.out.println("Roll Number: " + rollNumber);
System.out.println("Course: " + course);
}
}
class Teacher extends Person {
String teacherId;
String subject;
void displayTeacherDetails() {
displayBasicDetails();
System.out.println("Teacher ID: " + teacherId);
System.out.println("Subject: " + subject);
}
}
This example shows how inheritance helps avoid duplication. Common person details are written once in Person and reused by Student and Teacher.
Real-World Example: E-Commerce Product Hierarchy
In an e-commerce application, Product can be a parent class. ElectronicsProduct and ClothingProduct can inherit common product features and add their own specific details.
| Class | Common / Specific Properties | Common / Specific Methods |
|---|---|---|
| Product | productId, name, price, stockQuantity | displayProduct(), updateStock() |
| ElectronicsProduct | warrantyPeriod, brand | displayWarrantyDetails() |
| ClothingProduct | size, color, fabric | displaySizeDetails() |
Advantages of Inheritance
Inheritance provides many advantages in software development when used properly. It helps build reusable and organized class structures.
Benefits of Inheritance
- Code Reusability: Common code can be written once and reused by child classes.
- Reduced Duplication: Similar classes do not need repeated code.
- Better Organization: Related classes can be arranged in a hierarchy.
- Extensibility: New child classes can extend existing parent classes.
- Maintainability: Common logic can be updated in one place.
- Polymorphism Support: Inheritance helps enable runtime polymorphism through method overriding.
- Real-World Modeling: Parent-child relationships can model real-world categories.
- Cleaner Design: Common behavior is separated from specialized behavior.
- Consistency: Child classes can follow a common structure from the parent class.
- Faster Development: Existing classes can be extended instead of writing everything from scratch.
Limitations of Inheritance
Inheritance is powerful, but it should be used carefully. Poor inheritance design can make programs complicated and difficult to maintain.
Inheritance vs Composition
Inheritance represents an is-a relationship, while composition represents a has-a relationship. Both are used for code reuse, but they solve different design problems.
For example, a Car is a Vehicle, so inheritance may be suitable. But a Car has an Engine, so composition is more suitable for connecting Car and Engine.
| Basis | Inheritance | Composition |
|---|---|---|
| Relationship | Is-A relationship | Has-A relationship |
| Example | Car is a Vehicle | Car has an Engine |
| Purpose | Reuse and specialize parent class behavior | Build complex objects using smaller objects |
| Flexibility | Can be less flexible if hierarchy is rigid | Often more flexible for changing behavior |
| Best Use | When child truly is a type of parent | When object contains or uses another object |
How to Decide Whether to Use Inheritance
Before using inheritance, developers should check whether the relationship between classes is natural. Inheritance should not be used only because two classes share some code. The child class should truly be a specialized version of the parent class.
Use Inheritance When
- The child class is a specialized type of the parent class.
- There is a clear "is-a" relationship.
- Multiple classes share common behavior and structure.
- The parent class represents a meaningful general concept.
- The child class needs to reuse and possibly override parent behavior.
- The inheritance hierarchy is simple and understandable.
Avoid Inheritance When
- The relationship is only "has-a" instead of "is-a".
- You only want to reuse a small piece of code.
- The hierarchy becomes too deep or confusing.
- Child classes need very different behavior from the parent class.
- Changes in parent class frequently break child classes.
- Composition would make the design simpler and more flexible.
Inheritance Best Practices
Good inheritance design makes software easier to understand and maintain. Poor inheritance design can make code complicated. Beginners should follow simple best practices.
Best Practices for Inheritance
- Use inheritance only when there is a clear "is-a" relationship.
- Keep inheritance hierarchies simple and shallow.
- Place only common features in the parent class.
- Place specialized features in child classes.
- Avoid forcing unrelated classes into one inheritance hierarchy.
- Use meaningful class names such as Vehicle, Car, Employee, Manager.
- Use method overriding carefully and clearly.
- Prefer composition when the relationship is "has-a".
- Do not make every class inherit just to avoid code duplication.
- Keep parent classes stable and well-designed.
Common Mistakes Beginners Make
Beginners often use inheritance incorrectly. Understanding these mistakes helps improve OOP design and prevents confusing class structures.
Common Mistakes
- Using inheritance only to reuse code without a real "is-a" relationship.
- Creating very deep inheritance chains.
- Putting too many unrelated features in the parent class.
- Making child classes depend too much on parent class internals.
- Confusing inheritance with composition.
- Overriding methods without understanding parent behavior.
- Making all parent properties public instead of using proper access control.
- Creating child classes that do not logically belong to the parent class.
Better Approach
- Check whether the child class truly is a type of the parent class.
- Keep parent classes general and child classes specific.
- Use protected or public methods carefully for inheritance access.
- Use composition for "has-a" relationships.
- Keep inheritance hierarchy understandable.
- Override methods only when child behavior should be different.
- Use clear class names and method names.
- Design before writing code.
Mini Practice Activity
Try to identify parent classes, child classes, and inherited features from the following scenarios. This activity will help you understand inheritance practically.
| Scenario | Parent Class | Child Classes | Common Features |
|---|---|---|---|
| Transport System | Vehicle | Car, Bike, Bus | brand, speed, start(), stop() |
| School System | Person | Student, Teacher | name, age, contactNumber |
| Company System | Employee | Manager, Developer, Tester | employeeId, name, salary, work() |
| Banking System | Account | SavingsAccount, CurrentAccount | accountNumber, balance, deposit(), withdraw() |
| Shape Drawing App | Shape | Circle, Rectangle, Triangle | color, draw(), calculateArea() |
| E-Commerce System | Product | ElectronicsProduct, ClothingProduct | productId, name, price, stock |
Frequently Asked Questions
1. What is inheritance in OOP?
Inheritance is an OOP concept where one class can acquire or reuse the properties and methods of another class. It creates a parent-child relationship between classes.
2. Why is inheritance used?
Inheritance is used to reuse code, reduce duplication, organize related classes, and allow child classes to extend or customize parent class behavior.
3. What is a parent class?
A parent class is the class whose features are inherited by another class. It is also called a base class or superclass.
4. What is a child class?
A child class is the class that inherits features from another class. It is also called a derived class or subclass.
5. What is an Is-A relationship?
An Is-A relationship means the child class is a specialized type of the parent class. For example, a Car is a Vehicle, and a Dog is an Animal.
6. What is method overriding?
Method overriding occurs when a child class provides its own version of a method that already exists in the parent class.
7. What is the difference between inheritance and composition?
Inheritance represents an Is-A relationship, while composition represents a Has-A relationship. For example, a Car is a Vehicle, but a Car has an Engine.
8. Can a child class add new methods?
Yes. A child class can inherit parent methods and also define its own new methods and properties.
9. Should inheritance always be used for code reuse?
No. Inheritance should be used when there is a real Is-A relationship. If the goal is only code reuse, composition may sometimes be a better choice.
10. What is the main benefit of inheritance?
The main benefit of inheritance is code reusability. Common features can be written once in a parent class and reused by multiple child classes.
Summary
Inheritance is one of the core concepts of Object-Oriented Programming. It allows one class to inherit properties and methods from another class. The class that provides features is called the parent class, and the class that receives those features is called the child class.
Inheritance helps reduce code duplication, improve reusability, organize related classes, and support method overriding. It is commonly used when classes have a natural Is-A relationship, such as Car is a Vehicle, Dog is an Animal, and Student is a Person.
Although inheritance is powerful, it should be used carefully. Deep inheritance hierarchies and wrong parent-child relationships can make programs difficult to maintain. Developers should use inheritance only when the relationship is clear and meaningful.
Key Takeaway
Inheritance allows a child class to reuse and extend the properties and methods of a parent class. It supports code reusability, class hierarchy, and method overriding. Use inheritance when there is a clear Is-A relationship between classes.