Inheritance is one of the four fundamental Object-Oriented Programming (OOP) principles, alongside Encapsulation, Polymorphism, and Abstraction. Inheritance allows a class to inherit properties and behaviors (methods) from another class. This enables code reusability and a logical hierarchy.
What is Single Inheritance?
Single Inheritance refers to a situation where a class (child or derived class) inherits from only one superclass (parent or base class). In other words, a class can extend only one class in Java. This is a simple inheritance structure that maintains a clear and linear relationship between two classes.
class ParentClass {
// Parent class members
}
class ChildClass extends ParentClass {
// Child class members
}
//extends keyword is used to establish inheritance.
//The child class will acquire all non-private members of the parent class.
Code language: PHP (php)
Example: Single Inheritance in Java
Consider a scenario where Mahesh, a student at LotusJavaPrince, wants to model a simple inheritance structure in a banking application. He wants to create a base class Account
and a derived class SavingsAccount
that inherits from Account
.
// Base class class Account { int accountNumber; double balance; Account(int accountNumber, double balance) { this.accountNumber = accountNumber; this.balance = balance; } void displayAccountDetails() { System.out.println("Account Number: " + accountNumber); System.out.println("Balance: $" + balance); } } // Derived class class SavingsAccount extends Account { double interestRate; SavingsAccount(int accountNumber, double balance, double interestRate) { super(accountNumber, balance); this.interestRate = interestRate; } void displaySavingsAccountDetails() { displayAccountDetails(); // Accessing parent class method System.out.println("Interest Rate: " + interestRate + "%"); } } // Main class public class Main { public static void main(String[] args) { SavingsAccount savingsAccount = new SavingsAccount(12345, 1500.0, 3.5); savingsAccount.displaySavingsAccountDetails(); } } /* Account Number: 12345 Balance: $1500.0 Interest Rate: 3.5% */
Advantages of Single Inheritance:
-
Simplicity: Reduces complexity by maintaining a clear linear hierarchy.
-
Code Reusability: Allows derived classes to reuse existing code in the base class.
-
Easy to Debug: The structure is straightforward, making it easier to trace bugs.
Limitations:
-
Java does not support multiple inheritance (a class cannot inherit from more than one class) to avoid ambiguity and complexity.
Single inheritance is a fundamental concept in Java, establishing a clear parent-child relationship between classes, promoting code reuse, and maintaining a simple and logical class hierarchy.