This tutorial explains the concept of Inheritance in Java, related terms like ‘extends’ and ‘super’ keywords, subclass, superclass, Is-A, HAS-A relationships, etc.:
After learning about the three Pillars of OOP namely, Abstraction, Encapsulation, and Polymorphism in Java, we come to the last pillar of OOP i.e. inheritance.
Starting with this tutorial we will discuss inheritance in Java in the next couple of tutorials.
=> Read Through The Easy Java Training Series.
Table of Contents:
Inheritance In Java
Inheritance in Java can be defined as a technique or process in which one object of a class acquires the behavior and properties of another object. This is done by inheriting the class or establishing a relationship between two classes.
For example, a Frog is an amphibian. Like other animals of the Amphibian class, Frog might have many characteristics that are common to other animals. So here an Amphibian is a species and animals like frogs are its members.
If we have to represent the amphibian species and its members in a software representation using OOP, then what we will do is we will develop a class “Amphibian” containing properties or behavior that is common to amphibians in general.
This way we do not have to duplicate the common properties and behavior of every amphibian animal we describe. We will directly create a class each for amphibian animals and inherit from the Amphibian class as shown below.
So a general idea behind the feature “Inheritance” is that we can create new classes by inheriting from the already existing classes. By inheriting from the already existing classes, we get to use the properties and behavior of these classes. Besides, we can add more properties and/or behavior to our new class.
The inheritance feature depicts a “parent-child” connection or relationship in Java. The class from which the new class is inherited is called the “Parent class” while the new class is called the “Child class”.
Inheritance is mainly used:
- For method overriding so that we can achieve Read Through The Easy Java Training Series..
- To reuse the code. By inheriting from the already existing classes, we ensure the reusability of code.
Common Terminology Used In Inheritance
- Reusability: Mechanism by which new classes reuse fields or properties and methods of an existing class.
- Class: A class is a collection of objects that have common properties. A class can be viewed as a template or a blueprint for the objects.
- Sub Class/Child Class: A class that inherits from another class is a subclass or a child class or a derived class.
- Super Class/Parent Class: A class that is inherited by another class to acquire properties and methods is called a Parent class or superclass or a base class.
The following inheritance hierarchy is an example showing a superclass and subclass.
We have an Employee class with fields OrganisationName and EmployeeId. It can also have other fields like Employee name, department, and other employee details.
Then we derive another class named ‘SoftwareDeveloper” with the field’s salary and perks. The class SoftwareDeveloper class inherits from the Employee class, and hence it also acquires the properties of the Employee class.
As shown in the above diagram, here Employee class is a Super or Base class and SoftwareDeveloper is a subclass or derived class.
‘extends’ Keyword In Java
In Java, the keyword ‘extends’ is used to inherit the class.
The general syntax of Java inheritance is given below:
class SubClass extends SuperClass { //subclass methods and fields }
As shown above, the ‘extends’ keyword appears after the classname in the class declaration syntax.
The keyword ‘extends’ conveys that we are creating a new class ‘SubClass’ that will inherit the properties and behavior from ‘SuperClass’. In other words, the extends keyword indicates that we are building a new class SubClass on the existing functionality of the SuperClass.
The inheritance implemented with the ‘extends’ keyword is the class inheritance. In the next tutorial, we will discuss another keyword ‘implements’ using which we can inherit interfaces.
An example of the Employee-SoftwareDeveloper class that we have explained above can be represented as:
class Employee{ String OrganizationName; int EmployeeId; } class SoftwareDeveloper extends Employee{ float Salary; float Perks; }
IS-A And HAS-A Relationship
Consider the following class structure:
class Mammal{ } class Cow extends Mammal{ }
So how we can interpret the above structure? As the Cow class extends or inherits Mammal, we can say “Cow IS A Mammal” or “Cow IS A Kind of Mammal”. Hence whenever we express such relationships, that particular relationship is the “IS_A” relationship.
In the above structure, we used the inheritance hierarchy to express the fact that one kind is of another kind. So in the above structure, we used an inheritance to indicate the relationship between Cow and Mammal.
Similarly, we can express some more IS-A relationships as follows:
Given above are some of the common examples of relationships that we can express using inheritance in Java.
In general, the IS-A kind of relationship can be expressed using inheritance.
Now let’s see the example below:
In the above diagram, we see that a Vehicle is shown to have two parts i.e. Engine and Brake. So how we can put this scenario in words?
We can say that “a Vehicle contains an Engine and a Vehicle contains a brake”.
So what we are expressing here is not the “IS-A” relationship but a containment relationship wherein we specify one object as a part of another object.
In the above example, an engine is a part of the vehicle. It is not a “kind of” vehicle. This is the “HAS-A” or containment or composition relationship in Java. The Has-a relationship in Java is expressed by including an object as a member of the class.
So if we follow the same vehicle example above, then we can express it as below:
class Engine{ } class Brake { } class Vehicle{ Engine e; Brake b; }
So a Vehicle has an engine and a brake. By expressing the relationship in the above manner, we are not interested in the internal implementation of an Engine or brake. The vehicle class will let Engine and Brake classes know what is needed and those classes will provide it.
Like the IS-A relationship, the HAS-A relationship is also useful in reusing the code.
In this tutorial, we will discuss inheritance (IS-A) in detail, and in the next tutorial, we will discuss Containment or Composition (HAS-A).
Java Inheritance Example
Let’s implement a simple example in Java to demonstrate inheritance.
//example class demonstrating Inheritance in Java class BaseClass { public void display() { System.out.println("BaseClass::Display"); } } //create a new class from BaseClass class DerivedClass extends BaseClass { public void print() { System.out.println("DerivedClass::print"); } } class Main { public static void main(String[] args) { //create an object of DerivedClass DerivedClass d1 = new DerivedClass(); d1.display(); //call BaseClass method d1.print(); //call DerivedClass method } }
Output:
The above program shows a simple example of inheritance. A BaseClass with one method is declared. Then another class DerivedClass that extends BaseClass is declared. This class also has one method.
In the main method of the program, we create a DerivedClass object, and using this object we call the BaseClass as well as the DerivedClass method.
The output shows the messages printed by both methods. As DerivedClass extends the BaseClass and BaseClass method is public, it is visible to the DerivedClass.
‘super’ Keyword In Java
In Inheritance, we deal with superclasses or parent classes and child classes. If we have to immediately access superclass members including variables, methods, or constructors, then we need to have some mechanism. This mechanism of accessing the base class members is provided in Java using a “super” keyword.
So in which scenarios do we use the ‘super’ keyword in Java?
Enlisted below are scenarios in which a ‘super’ keyword can be helpful.
- When the super /base class and sub/derived class have the same names for members, and we want to access superclass members then we use the super keyword.
- When we want to access the superclass constructor from the subclass, then we use the super keyword to invoke the superclass keyword.
In the above figure, we have shown an inheritance structure. In the base as well as derived class, we have a String variable myStr. In the derivedClass, we have a printStr () function. In this method, we have used the ‘super’ keyword to access the myStr variable from the base class.
In the figure, we have shown the arrows pointing to the base class member variable and derived class variable.
Now let’s see the programming examples of using the super keyword to access various superclass members.
#1) Access Superclass Member Variable
The following Java program demonstrates the use of a ‘super’ keyword to access variables from the base class.
class Baseclass { String myStr; } class Subclass extends Baseclass { String myStr; public void printdetails() //Baseclass and Subclass have variables with same name { super.myStr = "Super"; //refers to parent class member myStr = "Sub"; System.out.println("Superclass myStr :" + super.myStr+" and Subclass myStr:"+myStr); } } class Main{ public static void main(String[] args) { Subclass cobj = new Subclass(); cobj. printdetails (); } }
Output:
The above program shows how to access the member variables of the base class from the derived class when the member variables are declared with the same name both in the base as well as derived class.
Here, we have myStr variable which is declared in the base as well as derived class. In the method printdetails, we refer to the myStr variable of the base class using “super.myStr” while the derived class variable myStr is accessed directly without any qualifier.
#2) Access Superclass Method
Next, we will see how to call the base class method when the method in the base class and the method in the derived class have the same names.
The following program demonstrates this.
class Parent { String myStr; public void print() //parent class method { myStr = "Parent class myStr"; System.out.println(myStr); } } class Child extends Parent { String myStr; public void print() //child class method with same name as parent { super.print(); //call Parent class print() method myStr = "Child class myStr"; System.out.println(myStr); } } class Main{ public static void main(String[] args) { Child c_obj = new Child(); c_obj.print (); } }
Output:
#3) Access Superclass Constructor
When we inherit one class from another, note that the constructors are not inherited.
If we want to execute any instructions from the superclass constructors before executing the derived class constructor then we can also call the superclass constructor using the ‘super’ keyword.
For calling the superclass constructor we use the method call.
super (parameter list…)
The following method demonstrates the access to super constructors in Java.
class Parent { String myStr; public Parent(String name) //base class constructor { myStr = name; } } class Child extends Parent { String myStr; public Child(String name1, String name2) { super(name1); //call base class constructor and pass argument value this.myStr = name2; } public void printDetails() //print details of both constructors { System.out.println("From base class constructor: " +super.myStr); System.out.println("From derived class constructor: " + myStr); } } class Main{ public static void main(String[] args) { Child cobj = new Child("Super constructor string","Child constructor string"); cobj.printDetails(); } }
Output:
As we can see from the above program, we have called the constructor of the superclass from the derived class constructor. Note that by convention, whenever we want to access the superclass constructor, it should be the first statement in the constructor of the derived class.
As the base class has a parameterized constructor, we also pass the appropriate parameter to the super call while calling the constructor.
If there is no explicit call made to the super constructor as above, then the compiler always adds an implicit call to super () automatically. But note that this will be a call to the default constructor of the superclass.
Frequently Asked Questions
What is Inheritance in Java?
A process by which one class acquires the properties and behavior of another class is called inheritance. In Java, one class is inherited by another class using the ‘extends’ keyword.
Inheritance promotes reusability of code as by inheriting we can acquire and use the already existing properties and behavior of an inherited class without having to write duplicate code.
Why is Inheritance used in Java?
Inheritance is mainly used to improve the reusability of the application. Using inheritance we can use ready classes in our application. We do not have to write our code if we have the functionality ready.
The second use of inheritance is in method overriding. To implement runtime polymorphism we make use of inheritance.
What are the Advantages of Inheritance?
Reusability is the key advantage of inheritance. Sharing of code through inheritance also results in better readability and better organization of code.
We can also achieve runtime polymorphism through method overriding using inheritance.
What are the features of Inheritance?
Any characteristic or feature acquired from the older generation is done through inheritance. For example, the light-eye trait that occurs in many families is an example of inheritance.
From a programming viewpoint, inheritance provides the feature of reusability and method overriding.
Is super () necessary?
No. Because if we don’t call super (), the compiler does it implicitly for us. But then implicit invocation of super () is the default base class constructor. So if we need a parameterized constructor from a base class, then we should call it explicitly.
Conclusion
In this tutorial, we introduced the concept of Inheritance in Java. Inheritance is the process of acquiring the properties and behavior of one class in another class. We discussed the basic definition and terminology we use in inheritance here.
We have also discussed the Is-A and Has-A relationships in Java. Inheritance is used to implement an Is-A relationship.
Then we discussed the ‘extends’ and ‘super’ keywords in Java that are used in connection with the inheritance. Extends are used to implement inheritance. The super keyword is used to refer to the base class constructor, method, or variable from the derived class.
=> Check Out The Perfect Java Training Guide Here.