Inheritance concept
Inheritance promotes the reusability of code by allowing classes to derive common characteristics from a base class. It enables the creation of hierarchical relationships between classes, where a child class can inherit and extend the functionality of its parent class. Subclasses can override or extend inherited methods, adding flexibility and specificity.
Bank Account Example:
To illustrate Inheritance, let’s extend our BankAccount class to create specialized types of accounts. For instance, we can create a SavingsAccount class that inherits from BankAccount and adds a specific interest rate.
classDiagram
class BankAccount {
- Int accountNumber
- Int balance
- String accountHolder
+ deposit(amount)
+ withdraw(amount)
+ getBalance()
}
class SavingsAccount {
- Float interestRate
+ applyInterest()
}
BankAccount <|-- SavingsAccountBankAccount provides shared attributes like accountNumber, balance, and accountHolder, along with shared methods like deposit(), withdraw(), and getBalance().SavingsAccount inherits all the properties and behaviors of BankAccount but adds its own interestRate🔒 attribute and the applyInterest()🔓 method.This example illustrates how Inheritance allows new classes to build on top of existing ones. The SavingsAccount class can leverage all the functionality of BankAccount while introducing its own features like calculating interest. By sharing common code between the parent and child classes, inheritance reduces redundancy and promotes a cleaner design.
Why Inheritance Matters?
Code Reusability
Inheritance helps avoid duplication by allowing multiple subclasses to inherit common functionality from a single parent class. This way, shared attributes and methods can be reused without having to rewrite them in each subclass.
Extensibility
Inheritance makes it easy to extend functionality. You can create new classes based on existing ones, introducing specialized behaviors while maintaining the foundational code from the parent class.
Maintainability
By organizing code into parent-child class relationships, Inheritance simplifies maintenance. Changes in the parent class automatically propagate to all subclasses, ensuring consistency across your application.
Hierarchical Organization
Inheritance naturally supports the creation of a class hierarchy. This makes it easier to understand and structure complex systems, particularly when there are multiple related classes.
Next Step:
Now that you’ve learned how Inheritance promotes code reusability and extensibility, the next step is to explore Polymorphism, which allows objects of different classes to be treated uniformly.