The objects are the building blocks of the object oriented programming language. A programmer may use multiple objects belonging to different classes in some situations, which may have some relationship among themselves as they share some common features.
Let us consider an example of a program containing objects of two different classes, Car and Motorcycle, for maintaining car and motorcycle information, respectively. Both Car and Motorcycle classes exhibit some relationship as both are vehicles and share some common features like speed, engine specification, etc. To represent the relationship between classes, we use the concept of Inheritance.
We’ll be covering the following topics in this tutorial:
What is Inheritance in Java
Inheritance in Java is one of the compile-time mechanisms in the Object-Oriented Programming language, enabling you to organize classes in a hierarchical form. Just like a child inherits his parents’ characteristics and adds certain new characteristics of his own.
A programmer can write a new class that can inherit the accessible fields and methods and may also add new fields and methods. The inclusion of members of the existing class in a new class so that they are accessible in the new class is known as class inheritance.
The existing class that is being inherited is called the superclass, and the new class that inherits the functionality is called the subclass. In some other programming languages, a superclass can also be referred to as a parent, base class, or an ancestor, and the subclass is referred to as a child, derived class, or a descendant.
Advantage of Inheritance
The main advantage of Inheritance is the reusability of the code. Inheritance allows well-tested code to be reused and enables changes to be made once and affect all relevant places. Once the superclass has been written, tested, and debugged properly, its functionality can be reused by the subclasses rather than being rewritten from scratch. The subclass inherits the members of the superclass and can add members of its own. Thus, it reduces the amount of new code that must be designed, written, and tested each time a program is developed. It also saves time and increases the reliability of the program.
The benefit of reusability is more visible in developing complex projects involving many programmers. Without Inheritance, programmers may spend most of their time rewriting code they have written many times before. But using the concept of Inheritance, the same code can be written only once in the superclass and can be reused by different programmers. In general, Inheritance provides the ability to extend an existing class to meet new requirements without affecting the original class in any way.
To illustrate the concept of Inheritance, let us consider the following diagram :
In the above diagram, Class X contains member A and B. Later on, if a Class Y is to be added in the program which contains identical members A and B to that of Class X along with an additional member C, then instead of writing the code for members A and B again in Class Y, it is better to inherit these members from an already existing Class X and only add additional member C in it as shown in the figure. Thus by inheriting the common features of the superclass into the subclass, the size of the code is reduced. It also helps to ensure consistency as common features do not exist in several classes and therefore, only need to be modified or tested once. The Class X from which the features are inherited is called the superclass and the Class Y that inherits the features is called the subclass.
In Fig, the arrow pointing in the upward direction from Class Y to Class X indicates that the Class Y is derived from the subclass Class X.
Implementing Inheritance
Inheriting a superclass gives a subclass the ability to define only those aspects that differ from or extend the superclass’s functionality. The syntax for creating a subclass is simple. At the beginning of your class definition, use the extends keyword after the class name followed by the name class being extended (i.e.superclass ). A subclass can only inherit directly from one superclass. Unlike C++, Java does not support multiple inheritances.
class SubClassName extends SuperClassName { // Additional member declarations }
Here, SubClassName is the subclass’s name, and SuperClassName is the superclass’s name whose members are inherited by the subclass. The extends keyword identifies that SuperClassName is the superclass for class SubClassName.
This keyword establishes an inheritance relationship between the two classes. The subclass body contains the member’s declaration for all the members that are not common to that of the superclass.
The member inherited in the subclass is a full member of that class and is freely accessible to any method in the class. When an object(s) of the subclass is instantiated, it will contain the members of its class and contain all the inherited members of the superclass from which it is derived.
To understand how a subclass is derived from the superclass, let us consider a program with a superclass named Base consisting of a data field num1 and a method baseShow(). Suppose you want to extend the functionality of Base by adding new members. For this, we create a subclass named Derived, which is derived from the Base. So it inherits all the accessible members of the Base. It also extends the functionality of the Base by adding its field num2 and methods product() and derivedShow(). These members are exclusive to the subclass and cannot be used by the object of the superclass.
// show the use of inheritance // super class class Base { int num1; void baseShow() { System.out.println("num1 = "+num1); } } //subclass of Base class class Derived extends Base { int num2; void product(){ System.out.println("Product = "+(num1 * num2)); } void derivedShow(){ System.out.println("num2 = "+num2); } } public class Main { public static void main(String[] args){ Derived d =new Derived(); d.num1 =20; d.baseShow(); d.num2 =10; d.derivedShow(); d.product(); } }
Output :
Here, class Base is the superclass, and the class Derived is its subclass. In the class header, ‘Derived extends Base’ means that the class Derived implicitly inherits the data fields and methods of class Base.
In other words, we can say that class Derived inherits the field num1 and the method baseShow () from the class Base. These members are freely accessible to any method of the class Derived as if they are members of that class. It can be seen in the method product () of the class ‘Derived,’ where the num1 field of class Base is referred to directly.
In the main() method, when the Derived object is created, it can access both num1 and num2 fields as well as can call methods baseShow(), derivedShow(), and product().
Inheritance and Access Specifiers
Inheritance is a mechanism of creating a new class from an existing class by inheriting the existing class’s features and adding additional features of its own.
When a class is derived from an existing class, all the superclass members are automatically inherited in the subclass. However, it is also possible to restrict access to the superclass’s fields and methods in the subclass. It is possible by applying the access specifiers to the member of the superclass. If you do not want a subclass to access a superclass member, give that member private access. The superclass’s private members remain private (accessible within the superclass only) in the superclass and hence are not accessible directly to the subclass members. However, the subclass can access them indirectly through the inherited accessible methods of the superclass.
Types of Inheritance in Java
Simple Inheritance
When a subclass is derived simply from it’s parent class then this mechanism is known as simple inheritance. In case of simple inheritance there is only a sub class and it’s parent class. It is also called single inheritance or one level inheritance.
class A { int x; iny y; int get(int p,int q) { x = p; y = q; return(0); } void Show() { System.out.println(x); } } class B extends A { public static void main(String args[]) { A a = new A(); a.get(5,6); a.Show(); } void display() { System.out.println("B"); } }
Multilevel Inheritance
It is the enhancement of the concept of inheritance. When a subclass is derived from a derived class, this mechanism is known as the multilevel inheritance. The derived class is called the subclass or child class for its parent class, and this parent class works as the child class for it’s just above ( parent ) class. Multilevel inheritance can go up to any number of levels.
class A { int x; int y; int get(int p,int q) { x = p; y = q; return(0); } void Show() { System.out.println(x); } } class B extends A { void Showb() { System.out.println("B"); } } class C extends B { void display () { System.out.println("C"); } public static void main(String args[]) { A a = new A(); a.get(5,6); a.Show(); } }
Hierarchical Inheritance
The existing class is inherited by one or more child classes (subclasses) then such kind of inheritance is known as hierarchical.
In the above program, Class B, C, and D are the subclasses that inherit the super class’s functionality, i.e., Class A.
class Shape { public void Shaped() { System.out.println("Base Class - Shape"); } } class Rectangle extends Shape { public void Rectangled() { System.out.println("Derived Class - Rectangle"); } } class Triangle extends Shape { public void Triangled() { System.out.println("Derived Class - Triangle"); } } class Circle extends Shape { public void Circled() { System.out.println("Derived Class - Circle"); } } class JavaExample { public static void main(String args[]) { Rectangle Rect = new Rectangle(); Triangle Tri = new Triangle(); Circle Cir = new Circle(); //All classes can access the method of class Shape Rect.Shaped(); Tri.Shaped(); Cir.Shaped(); } }
Hybrid Inheritance
It is the combination of two or more types of inheritance.
What is the importance of Inheritance in java?
• Code reusability: It is a fundamental feature of inheritance. It allows us to reuse code that already exists rather than repeatedly writing and creating identical codes. Not only does this save a great deal of time and money because the properties are reused, but it also makes our code a great deal more reliable.
• Method Overriding: When we use inheritance, we can override the methods in our base class, making the base class more comfortable to use in a derived class.
• When both a parent and a child class have identical data members, inheritance becomes known as data hiding.
• When both a parent and a child class have the same functions, inheritance becomes known as method overriding.
• When both a parent and a child class have the same static functions, inheritance becomes known as function hiding.
• You cannot print the super keyword; if you tried, you would get a syntax error. The child class uses the super keyword to inherit the data members of a parent class.
• If a non-static function is made as final in any class, the child class might not override it.