Inheritance with Java Examples
Overview
In this post, we will learn about Inheritance and different forms of it with examples. Inheritance is the most important and powerful feature of object-oriented programming. Using inheritance we can create new classes called sub-classes or derived classes from existing superclass or parent class.
‘IS-A’ or ‘is-an’ relationship
As a rule of thumb, we use inheritance when the classes have ‘is-a’ relationship. Let’s consider an example to understand the rule. Let say we have an Animal superclass and a Cat class. Now, try to affirm that Cat ‘is-a’ or /’is-an’ Animal? True
So, we can go ahead and use inheritance to design the Cat class that extends the Animal class. In Java we use the keyword “extends” to extend a class from an existing superclass.
‘HAS-A’ or ‘has-an’
Now lets consider another example.
Consider class Fan and another class Capacitor. Using the same rule try to ask yourself, Capacitor is a Fan? No
The answer is no this time. So, we may not use the inheritance relationship between the two classes. Even though every fan has a capacitor part inside it. We use the aggregation relationship. Fan ‘has a’ capacitor part in it.
Single and Multiple Inheritance
When a class is derived or subclassed from one base/super class then it’s called Single Inheritance.
On the other hand,when a sub class is derived from two or more super classes then its called multiple inheritance. One key point to remember here is that Java doesn’t support multiple inheritance directly. We may need to use interfaces to come across this limitation.
Multi-level Inheritance
When a class is derived from a class which is also derived from a parent class as shown in the picture, this type of inheritance is called multi-level inheritance.
Sample Java Code
package inheritance; public class BaseClass { public String classInfo() { return "BaseClass"; } }
Derived Class
package inheritance; public class DerivedClass extends BaseClass { @Override public String classInfo() { return "DerivedClass"; } public void extraFunctionality() { System.out.println("This class is derived from " + super.classInfo()); } //main method public static void main(String[] args) { DerivedClass dc= new DerivedClass(); dc.extraFunctionality(); } }
Java Tutorial on this website: https://www.testingdocs.com/java-tutorial/
For more information on Java, visit the official website :