Bachelor of Science in Computer Science
Course ContentInheritance
Habari Mwanafunzi! Welcome to the World of Inheritance!
Have you ever been told, "You have your mother's eyes" or "You walk just like your father"? In Kenya, we understand family and legacy very well. We inherit names, land, and even certain traits from our parents and grandparents. It's a natural way of passing things down through generations.
Well, get ready, because in Object-Oriented Programming, our code can do the exact same thing! This powerful idea is called Inheritance, or in Kiswahili, "Urithi". It's one of the cornerstones of OOP, and by the end of this lesson, you'll see how it makes our code smarter, cleaner, and much easier to manage. Let's begin!
So, What Exactly is Inheritance?
In Java, inheritance is a mechanism where one class (the child) acquires the properties (variables) and behaviors (methods) of another class (the parent).
Think of it like a family tree for your code.
- The class whose features are inherited is known as the Superclass (or Parent class).
- The class that inherits the other class is known as the Subclass (or Child class).
The key idea is "is-a" relationship. For example, a TukTuk is-a type of Vehicle. A Lion is-a type of Animal. This relationship is what makes inheritance so logical.
+----------------+
| SUPERCLASS | (e.g., Vehicle)
| (Parent) |
+----------------+
^
|
| (Inherits from)
|
+----------------+
| SUBCLASS | (e.g., TukTuk)
| (Child) |
+----------------+
Why Should We Care? The "So What?" of Inheritance
Using inheritance is like being a smart farmer instead of a tired one. Instead of planting every single seed by hand every time, you use tools and techniques passed down to you to make your work efficient. Here are the main benefits:
- Code Reusability: This is the big one! You can write common code once in a parent class and reuse it across multiple child classes. This follows the "Don't Repeat Yourself" (DRY) principle. No more copy-pasting!
- Method Overriding: A child class can provide a specific implementation for a method that is already defined in its parent class. This allows for more specialized behavior. We'll see this in a moment!
- Better Organisation: It helps create a clear and logical structure in your code, just like a family tree helps you understand your relatives.
Real-World Scenario: Imagine you're building a system for a school. You have Students, Teachers, and Cleaners. All of them have a `firstName`, `lastName`, and an `idNumber`. Instead of writing these three variables in three separate classes, you can create a single `Person` class. Then, `Student`, `Teacher`, and `Cleaner` can all inherit from `Person`. If you need to add a `phoneNumber` later, you only add it to the `Person` class once! Easy, right?
How to Do It in Java: The extends Keyword
To create a subclass, you simply use the extends keyword. It's like telling Java, "Hey, this new class I'm making is a child of that other class."
// This is the general syntax
class SuperclassName {
// ... methods and fields
}
class SubclassName extends SuperclassName {
// ... methods and fields
}
Example Time: Modeling M-PESA Accounts
We all use M-PESA. Let's model it! A basic M-PESA account has some common features. A business till, which is a specialized type of account, has all those features PLUS some unique ones.
> Image Suggestion: An illustration showing a large, generic M-PESA green logo block. Arrows point from it to two smaller blocks: one labeled "Personal Account" with a person icon, and another labeled "Business Till" with a shop icon. The style should be a simple, clean, flat graphic design.
First, let's create the parent class, MpesaAccount.
// File: MpesaAccount.java
public class MpesaAccount {
String phoneNumber;
double balance;
public MpesaAccount(String phoneNumber, double initialBalance) {
this.phoneNumber = phoneNumber;
this.balance = initialBalance;
}
public void deposit(double amount) {
if (amount > 0) {
balance += amount;
System.out.println("Deposited KES " + amount + ". New balance is KES " + balance);
}
}
public void checkBalance() {
System.out.println("Account " + phoneNumber + " has a balance of KES " + balance);
}
}
Now, let's create a child class, BusinessTill, that inherits from it.
// File: BusinessTill.java
// Notice the "extends" keyword!
public class BusinessTill extends MpesaAccount {
String tillNumber;
// The constructor for the child class
public BusinessTill(String phoneNumber, double initialBalance, String tillNumber) {
// 'super()' calls the constructor of the parent class (MpesaAccount)
super(phoneNumber, initialBalance);
this.tillNumber = tillNumber;
}
// A method unique to BusinessTill
public void generateStatement() {
System.out.println("Generating statement for Till No: " + tillNumber);
// In a real app, this would do much more!
}
}
Now let's see how we can use them in a main program.
// File: Main.java
public class Main {
public static void main(String[] args) {
// Create a parent class object
MpesaAccount personalAcc = new MpesaAccount("0712345678", 500.00);
personalAcc.checkBalance();
personalAcc.deposit(1000);
System.out.println("---------------------------");
// Create a child class object
BusinessTill myDuka = new BusinessTill("0722000111", 10000.00, "123456");
// We can use methods from the parent class!
myDuka.checkBalance();
myDuka.deposit(5000);
// And we can use methods from the child class itself!
myDuka.generateStatement();
}
}
See? The myDuka object, which is a BusinessTill, could use checkBalance() and deposit() without us ever writing that code inside the BusinessTill class. That is the power of urithi!
Types of Inheritance in Java
Java keeps things organized with a few types of inheritance.
// 1. Single Inheritance (One child, one parent)
// Class B extends Class A
// (Our M-PESA example is this type)
[ A ]
^
|
[ B ]
// 2. Multilevel Inheritance (A chain of inheritance)
// Class C extends B, Class B extends A
// Like Guka -> Baba -> Kijana
[ A ]
^
|
[ B ]
^
|
[ C ]
// 3. Hierarchical Inheritance (One parent, many children)
// Class B extends A, Class C also extends A
// Like a Vehicle being a parent to Car, Motorbike, and TukTuk
[ A ]
/ \
/ \
[ B ] [ C ]
Important Note: Java does not support Multiple Inheritance (one class inheriting from two different parent classes directly). This is to avoid a complex issue called the "Diamond Problem." Don't worry about it for now, just know that we use something called Interfaces to achieve a similar result, which you will learn about later!
The "super" Powerful Keyword
You saw the super keyword in our BusinessTill example. It's a special reference variable used to refer to the immediate parent class object.
super(parameters): Calls the constructor of the parent class. It must be the very first line in the child class's constructor.super.methodName(): Calls a method from the parent class. This is useful in method overriding when you want to run the parent's code *and* add new code.
Let's Wrap It Up!
Hongera! You've just grasped one of the most fundamental concepts in OOP. Inheritance is all about creating "is-a" relationships to reuse code and build logical, easy-to-manage applications. It's the secret to writing less code that does more work.
Your Challenge: Let's go on a small safari! Think about a parent class calledAnimalwith properties like `name` and `species`, and a method like `makeSound()`. Can you create two child classes,LionandZebra, that extendAnimal? Give them unique properties (e.g., `maneColor` for Lion, `stripeCount` for Zebra) and override the `makeSound()` method to make a "Roar!" and a "Neigh!".
Keep practicing, and you'll see that inheritance is not just a programming concept; it's a way of thinking that helps you solve complex problems elegantly. Tukutane in the next lesson!
Pro Tip
Take your own short notes while going through the topics.