Inheritance In Java: Inheritance Types With Example

May 09, 2022
Xblog InheritanceinJava



Overview

Inheritance is not a new thing for any Java developer as it is one of the most fundamental concepts of object-oriented programming. Inheritance concepts are everywhere in Java programming. It is a mechanism that allows a class to acquire the property of another class. Just like a child inherits the traits of his parents. Due to this, inheritance significantly facilitates reusability in a program.

Inheritance in Java is not any different. It allows a class to acquire all the properties and behaviors of another class. The class from which the properties are inherited is commonly known as the superclass or the parent class. The basic idea behind Java inheritance is that it allows a Java developer to create new classes that are based upon already existing classes. When an existing class has been inherited, all the methods and fields of the parent class can be easily reused. Moreover, new methods and fields can also be added to the current class.

Further in this article, we will be discussing different types of inheritance in Java that can be applied in a java program and what sort of unique feature is offered by each of them. For your better understanding, several examples are accompanied with each type of Java inheritance.

explore new Java roles

The basic syntax of Inheritance in Java

1.class class_A extends class_B  
2. {  
3.   //new methods and fields of class_A
4. }

Here, class_A is a new class or the subclass to be made and class_B is the class to be inherited or the superclass. The “extends” keyword used in Java inheritance indicates the class inheritance. It expresses that the class to be made is derived from an existing class and all its fields and methods will be accessible by this new class.

Types of Java Inheritance

The different types of Java Inheritance are as follows:

  • Single Inheritance
  • Multi-Level Inheritance
  • Hierarchical Inheritance
  • Multiple Inheritance (Using Java Interface)
  • Hybrid Inheritance (Using Java Interface)

Single Inheritance

Single inheritance is the most basic type of Java Inheritance. Extending a subclass from a single superclass is called single inheritance.

1.class Residential_lot{  
2. int sizeInSqFt=8000;  
3. // Setter and getter methods
4. }  
5. class Apartment_Building extends Residential_lot{  
6. int Floors=0;
7. int noOfApartments = 0;
8. int noOfRentals = 0;
9. // Setter and getter methods
10.}
11.Class SingleInheritance{
12. public static void main(String args[]){  
13.  Apartment_Building ab01=new Apartment_Building();  
14.  ab01.SetFloors(15);
15.  System.out.println("Number of floors in the building:"+ab01.Floors);  
16.  System.out.println("Size of Lot of Building in Square feet:"+ab01.sizeInSqFt);  
17. }    
18.}

The output will be:

Number of floors in the building: 15
Size of Lot of Building in Sq feet: 8000


In the above code example, Apartment_Building has inherited a single class which is Residential_Lot. The objects of Apartment_Building class can access the field of its class as well as of the Residential_Lot class. This is also a very basic example of code reusability as it does not require repeating the sizeInSqFt field in the new class. It is often referred to as the “IS-A” relationship between classes.

Multilevel Inheritance

In Multi-Level Java Inheritance, a new subclass extends to a class that is already extended from another superclass. An ideal example of multilevel inheritance is the relation between a child his father and his grandfather.

Let’s take an example of three classes, class Student, class Degree, and class Majors. Here, the class Student is the Superclass. The class Degree extends the Student class and lastly, the Majors class extends the Degree class.

See this code demonstration below:

1.class Student{  
2.String Student_ID = “ ”;
3.String Student_Name = “ ”;
4.String Student_PhoneNo = “ ”;
5.String Student_Address = “ ”;
6.// Setter and getter methods
7.}  
8.class Degree extends Student{  
9. String Degree_Title = “ ”;
10. Int semester = 0;
11. Float SGPA = 0.0;
12. Float CGPA = 0.0;  
13. // Setter and getter methods
14.}  
15. class Majors extends Degree{  
16. String Majors = “ “;
17. Boolean ThesisCompleted = False;
18. // Setter and getter methods
19. }
20. Class MultilevelInheritance{
21. public static void main(String args[]){  
22. Majors std34=new Majors();  
23. Std34.SetName(“Sam Ralph”);
24. Std34.SetDegree(“Computer Science”);
25. Std34.SetMajors(“Data Science”);
26. } 
27.}

Multi-level inheritance takes the reusability factor to another level as now fields and methods can be accessed by various classes on different levels. It works very similarly to the single inheritance but with added levels. Multi-level Inheritance can go up to several levels in java depending on the requirements of your code.

Hierarchical Inheritance

Hierarchical Inheritance has a bit different approach than the previous types. In this type, the inheritance does not grow downwards instead it is applied in scenarios where classes extend sideways. Here, multiple subclasses inherit from a single superclass. In simple words, more than one child class extends a single parent class or a single parent class has more than one child class.

For example, consider a parent vehicle class. It can have multiple child classes like Car class, Bike class, Bus Class, and many more. In a Hierarchical Java Inheritance, multiple subclasses can now extend a single superclass of Vehicles.

1.class Vehicles{  
2.String RegistrationNo = “ ”;
3.String EngineNo = “ ”;
4.Int SeatingCapacity = 0;
5.Int HorsePower = 0;
6.}  
7.class Car extends Vehicles{  
8.String Color = “ ”;
9.String Brand = “ “;
10.// Setters and getter methods
11.}
12.class Bus extends Vehicles{  
13.String PermitNo = “ “;
14.// Setters and getter methods
15.}
16.class HierarchicalInheritance{
17.public static void main(String args[]){  
18.Bus vc03=new Bus();  
19.vc03.SetSeatingCapacity(24);
20.vc03.SetPermitNo(“ck1234”);
21.Car vc04 = new Car();
22.vc04.SetSeatingCapacity(4);
23.vc04.SetColor(“Black”);
24.}
25.}

Multiple Inheritance

Defining a subclass that inherits numerous superclasses is called ‘Multiple Inheritance’. In this case, there is more than one superclass, and there can also be one or more subclasses in this type of inheritance.

Multiple inheritances are available in various other object-oriented programming languages but it is not available in Java. The reason behind this was to keep the complexity minimal and to simplify the programming language.

Consider a scenario where c1, c2, and c3 are three classes. Class c3 inherits class c2 and class c3. In case, if c1 and c2 classes have the method with the same name that is possible and you also call it from a subclass object, this will cause ambiguity as the compiler will not be able to determine whether to call the method of c1 class or c2 class. This will result in a compile-time error.

To bypass this, multiple inheritances can be implemented in Java using an interface. An interface contains variables and methods just like a class but the methods in an interface are abstract by default. Multiple inheritances using an interface is implemented by implementing multiple interfaces by a class or if an interface itself extends multiple interfaces.

See this code demonstrating multiple inheritances using an interface in Java:

1.interface Volunteer{
2.   String voltID = “ ”;
3.//Setter and getter methods
4.}
5.interface Intern {
6.   String internID = “ “;
7.//Setter and getter methods
8.}
9.class Student implements Volunteer, Intern {
10. .
11. .
12. .
13. .
14.}
15.public class multipleInheritance {
16.   public static void main(String args[]) {
17.      Student std054 = new Student();
18.      Std054.SetVoltId(“vt15”);
19.      Std054.SetInternID(“int09”);
20.   }
21.}

Hybrid Inheritance

Hybrid Java Inheritance is a combination of different Inheritances. More than one type of inheritance is implemented here. For instance, if we have class c03 and class c02 that extend class c01 and there is another class c05 that extends class c01, then this type of Inheritance will be Hybrid Inheritance as it includes two kinds of Java inheritance, Hierarchical as well as Single Inheritance.

See Also: Writing a Parser In Java

Method Overriding in Java Inheritance

Other than acquiring the fields and methods, you can also override a method using Java inheritance. In method overriding, the child class must have the same method as that of the parent class but with a different definition.

It is used to provide a specific implementation of a particular method that was provided by the parent class, although there are certain rules for Method overriding that must be followed like:

  • Methods must share the same name in child and parent class.
  • It must have the same parameter as in the superclass.
  • There must be an IS-A type of Inheritance.

Conclusion

This was a brief overview of using inheritance in Java. You can implement different types of inheritance as per your requirement. The goal should be prioritizing reusability in your code and maintain the rules of OOP.

new Java jobs



author

admin


Candidate signup

Create a free profile and find your next great opportunity.

JOIN NOW

Employer signup

Sign up and find a perfect match for your team.

HIRE NOW

How it works

Xperti vets skilled professionals with its unique talent-matching process.

LET’S EXPLORE

Join our community

Connect and engage with technology enthusiasts.

CONNECT WITH US