OOPC - Inheritance (class – class)
![]() |
For example, imagine a child inherits a car from a parent. The child can use the car as it was inherited or modify its features as needed. However, once the car has been modified, it is no longer possible to revert to the exact original state of the car.
In programming, when we modify inherited features and behaviors, the original structure remains unchanged. We can always access the original version of the inherited class without affecting its original state.
This concept is analogous to inheritance in Object-Oriented Programming (OOP). In Java, inheritance can occur in several scenarios:
- class – class (extends)
- class – abstract class (extends)
- class – interface (implements)
- abstract class – interface (implements)
- interface – interface (extends)
1. class – class (extends)
Lets take the previous example. When we represent this inheritance type in java first we need to develop 2 separate classes for each entity associated with this scenario (parent and child). Lets say the parent has the following properties (variables) and behaviors (methods).
So, the parent need to have a behavior called driveCar() and 2 properties called carName and carModel
We can develop parent class as follows:
Now, let's assume that the child class needs to have the same details as the parent class, such as the ability to drive a car and the associated properties (name and carModel). Instead of rewriting the same code, we can use inheritance. The child class will extend the parent class, which means it will automatically inherit the properties with relevant values and behaviors of the parent class.
We can develop child class as follows:
driveCar()
method to provide a customized message when the child drives the car.Now, let’s see how this inheritance structure works in practice by creating objects of both the Parent and Child classes:
The Parent object uses the driveCar
()
method from the Parent class. So, the output is: John is driving a Toyota Corolla.()
method from the Parent class but uses its overridden version, resulting in the output: John is driving the Modified Toyota Corolla.To Summerize:
- Reuse code without duplicating it.
- Modify or extend behavior without changing the original class.
With inheritance, the child class gets all the properties and methods from the parent class. In the case of the child class, it can use the inherited methods and variables as it is or can modify them as needed without affecting parent class code.
Comments
Post a Comment