Inheritance in Java


Inheritance is one of the key features of Object-oriented programming in java. It allows user to create a new class (derived class) from an existing class(base class).

The derived class inherits all the features from the base class and can have additional features of its own.

Why inheritance should be used?

Suppose, in your game, you want three characters - a maths teacher, a footballer and a businessman.

Since, all of the characters are persons, they can walk and talk. However, they also have some special skills. A maths teacher can teach maths, a footballer can play football and a businessman can run a business.

You can individually create three classes who can walk, talk and perform their special skill

In each of the classes, you would be copying the same code for walk and talk for each character.

If you want to add a new feature - eat, you need to implement the same code for each character. This can easily become error prone (when copying) and duplicate codes.

It'd be a lot easier if we had a Person class with basic features like talk, walk, eat, sleep, and add special skills to those features as per our characters. This is done using inheritance.

Using inheritance, now you don't implement the same code for walk and talk for each class. You just need to inherit them.

So, for Maths teacher (derived class), you inherit all features of a Person (base class) and add a new feature TeachMaths. Likewise, for a footballer, you inherit all the features of a Person and add a new feature PlayFootball and so on.

This makes your code cleaner, understandable and extendable.

It is important to remember: When working with inheritance, each derived class should satisfy the condition whether it "is a" base class or not. In the example above, Maths teacher is a Person, Footballer is a Person. You cannot have: Businessman is a Business.

Terms used in Inheritance
  • Class: A class is a group of objects which have common properties. It is a template or blueprint from which objects are created.

  • Sub Class/Child Class: Subclass is a class which inherits the other class. It is also called a derived class, extended class, or child class.

  • Super Class/Parent Class: Superclass is the class from where a subclass inherits the features. It is also called a base class or a parent class.

  • Reusability: As the name specifies, reusability is a mechanism which facilitates you to reuse the fields and methods of the existing class when you create a new class. You can use the same fields and methods already defined in the previous class.

The syntax of Java Inheritance
class Subclass-name extends Superclass-name { //methods and fields }

The extends keyword indicates that you are making a new class that derives from an existing class. The meaning of "extends" is to increase the functionality.

In the terminology of Java, a class which is inherited is called a parent or superclass, and the new class is called child or subclass.

Java Inheritance Example
Inheritance in Java

As displayed in the above figure, Programmer is the subclass and Employee is the superclass. The relationship between the two classes is Programmer IS-A Employee. It means that Programmer is a type of Employee.

class Employee{ float salary=80000; } class Programmer extends Employee{ int bonus=20000; public static void main(String args[]){ Programmer p=new Programmer(); System.out.println("Programmer salary is:"+p.salary); System.out.println("Bonus of Programmer is:"+p.bonus); } }


Output:
Programmer salary is:80000.0 Bonus of programmer is:20000
Types of inheritance in java

On the basis of class, there can be three types of inheritance in java: single, multilevel and hierarchical.

In java programming, multiple and hybrid inheritance is supported through interface only. We will learn about interfaces later.

Types of inheritance in Java
Note: Multiple inheritance is not supported in Java through class.

When one class inherits multiple classes, it is known as multiple inheritance. For Example:

Multiple inheritance in Java
Single Inheritance

Single inheritance enables a derived class to inherit properties and behavior from a single parent class. It allows a derived class to inherit the properties and behavior of a base class, thus enabling code reusability as well as adding new features to the existing code. This makes the code much more elegant and less repetitive. Inheritance is one of the key features of object-oriented programming (OOP).

Single inheritance is safer than multiple inheritance if it is approached in the right way. It also enables a derived class to call the parent class implementation for a specific method if this method is overridden in the derived class or the parent class constructor.

Single Inheritance : In single inheritance, subclasses inherit the features of one superclass. In image below, the class A serves as a base class for the derived class B.

Example
class Animal{ void eat(){System.out.println("eating...");} } class Dog extends Animal{ void bark(){System.out.println("barking...");} } class TestInheritance{ public static void main(String args[]){ Dog d=new Dog(); d.bark(); d.eat(); } }


Output:
barking... eating...
Multilevel Inheritance

Multilevel Inheritance : In Multilevel Inheritance, a derived class will be inheriting a base class and as well as the derived class also act as the base class to other class. In below image, the class A serves as a base class for the derived class B, which in turn serves as a base class for the derived class C. In Java, a class cannot directly access the grandparent’s members.

Example
class Animal{ void eat(){System.out.println("eating...");} } class Dog extends Animal{ void bark(){System.out.println("barking...");} } class BabyDog extends Dog{ void weep(){System.out.println("weeping...");} } class TestInheritance2{ public static void main(String args[]){ BabyDog d=new BabyDog(); d.weep(); d.bark(); d.eat(); }}


Output:
weeping... barking... eating...
Hierarchical Inheritance

Hierarchical Inheritance : In Hierarchical Inheritance, one class serves as a superclass (base class) for more than one sub class.In below image, the class A serves as a base class for the derived class B,C and D.

Example
class Animal{ void eat(){System.out.println("eating...");} } class Dog extends Animal{ void bark(){System.out.println("barking...");} } class Cat extends Animal{ void meow(){System.out.println("meowing...");} } class TestInheritance3{ public static void main(String args[]){ Cat c=new Cat(); c.meow(); c.eat(); //c.bark();//C.T.Error }}


Output:
meowing... eating...
Why multiple inheritance is not supported in java?

To reduce the complexity and simplify the language, multiple inheritance is not supported in java.

Consider a scenario where A, B, and C are three classes. The C class inherits A and B classes. If A and B classes have the same method and you call it from child class object, there will be ambiguity to call the method of A or B class.

Since compile-time errors are better than runtime errors, Java renders compile-time error if you inherit 2 classes. So whether you have same method or different, there will be compile time error.

class A { void msg(){System.out.println("Hello");} } class B{ void msg(){System.out.println("Welcome");} } class C extends A,B{//suppose if it were Public Static void main(String args[]){ C obj=new C(); obj.msg();//Now which msg() method would be invoked? } }


Output:
Compile Time Error
Java and Multiple Inheritance

Multiple Inheritance is a feature of object oriented concept, where a class can inherit properties of more than one parent class. The problem occurs when there exist methods with same signature in both the super classes and subclass. On calling the method, the compiler cannot determine which class method to be called and even on calling which class method gets the priority.

Why Java doesn’t support Multiple Inheritance?
Consider the below Java code. It shows error.
// First Parent class class Parent1 { void fun() { System.out.println("Parent1"); } } // Second Parent Class class Parent2 { void fun() { System.out.println("Parent2"); } } // Error : Test is inheriting from multiple // classes class Test extends Parent1, Parent2 { public static void main(String args[]) { Test t = new Test(); t.fun(); } }


Output:
Compiler Error

From the code, we see that, on calling the method fun() using Test object will cause complications such as whether to call Parent1’s fun() or Parent2’s fun() method.

Hybrid Inheritance(Through Interfaces)

It is a mix of two or more of the above types of inheritance. Since java doesn’t support multiple inheritance with classes, the hybrid inheritance is also not possible with classes. In java, we can achieve hybrid inheritance only through Interfaces.

Important facts about inheritance in Java
  • Default superclass: Except Object class, which has no superclass, every class has one and only one direct superclass (single inheritance). In the absence of any other explicit superclass, every class is implicitly a subclass of Object class.

  • Superclass can only be one: A superclass can have any number of subclasses. But a subclass can have only one superclass. This is because Java does not support multiple inheritance with classes. Although with interfaces, multiple inheritance is supported by java.

  • Inheriting Constructors: A subclass inherits all the members (fields, methods, and nested classes) from its superclass. Constructors are not members, so they are not inherited by subclasses, but the constructor of the superclass can be invoked from the subclass.

  • Private member inheritance: A subclass does not inherit the private members of its parent class. However, if the superclass has public or protected methods(like getters and setters) for accessing its private fields, these can also be used by the subclass.

What all can be done in a Subclass?

In sub-classes we can inherit members as is, replace them, hide them, or supplement them with new members:

  • The inherited fields can be used directly, just like any other fields.

  • We can declare new fields in the subclass that are not in the superclass.

  • The inherited methods can be used directly as they are.

  • We can write a new instance method in the subclass that has the same signature as the one in the superclass, thus overriding it (as in example above, toString() method is overridden).

  • We can write a new static method in the subclass that has the same signature as the one in the superclass, thus hiding it.

  • We can declare new methods in the subclass that are not in the superclass.

  • We can write a subclass constructor that invokes the constructor of the superclass, either implicitly or by using the keyword super.




Instagram