Inheritance In Java

Inheritance In Java is the process by which one object acquires the properties of another object. Object-oriented programming allows classes to inherit commonly used state and behavior from other classes.

The idea of Inheritance In Java is simple but powerful, when you want to create a new class and there is already a class that includes some of the code that you want, you can derive your new class from the existing class. In doing this, you can reuse the fields and methods of the existing class without having to write (and debug!) them yourself.

For Example, as you can see in the below image Vehicle properties are inherited by Two wheeler, Three wheeler, and Four wheeler. Here we can state that any type of transportation will inherit the property of Vehicle. So, we can also say Vehicle is Parent and its children like two, three or four wheeler will inherit mandatory properties of Vehicle. Same things implies in JAVA, we create a class A which is having some defined methods, now there is a subclass class B which is inheriting the properties of A. So for class B it is mandatory to have all methods(properties) of parent class A along with its own methods.

In Inheritance in Java Excepting Object, which has no super-class, every class has one and only one direct super-class (single inheritance). In the absence of any other explicit super-class, every class is implicitly a subclass of Object.

A subclass inherits all the members (fields, methods, and nested classes) from its super-class.

Constructors are not members, so they are not inherited by sub-classes, but the constructor of the super-class can be invoked from the subclass.

Important terminology:

  • Super Class: The class whose features are inherited is known as a superclass(or a base class or a parent class).
  • Sub Class: The class that inherits the other class is known as a subclass(or a derived class, extended class, or child class). The subclass can add its own fields and methods in addition to the super-class fields and methods.
  • Reusability: Inheritance supports the concept of “reusability”, i.e. when we want to create a new class and there is already a class that includes some of the code that we want, we can derive our new class from the existing class. By doing this, we are reusing the fields and methods of the existing class.
  • The keyword used for inheritance is extends.

Function Overloading: Defining function again with

  • Same Name.
  • Different Arguments (number, sequence, type).
  • Same Class.

Function Overriding: Defining function again with

  • Same Name.
  • Same Arguments (number, sequence, type).
  • Base and Derived Class.

From the view of the derived class, there are 3 categories of methods in the base class :

  • Constructors
    • To call constructors of base class, “super” keyword is used
    • syntax : super(<args>);
    • Note: only constructors of the derived class can call constructors of the base class (first line)
  • Overridden Functions
    • To call overridden functions of base class, syntax is : super.functionName(<args>);
  • Remaining/Normal Functions
    • To call remaining functions, the syntax is : functionName(<args>);

Types of Inheritance in Java :

Below are the different types of inheritance which are supported by Java.

  • Single Inheritance:

In single inheritance, sub-classes inherit the features of one super-class. In the image below, 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 barko 
          {
            System.out.println("barking");
          }
    }
class Testlnheritance 
   {
        public static void main(String args[]) 
         {
           Dog d = new Dog();
           d.bark();
           d.eat();
         }
   }

Output:

barking
eating
  • Multilevel Inheritance:

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, 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 weepo
   {
     System.out.println("weeping");
   }
}
class Testlnheritance2
{
   public static void main(String args[])
  {
    BabyDog d = new BabyDog();
    d.weep();
    d.bark();
    d.eat();
  }
}

Output:

weeping
barking
Eating
  • Hierarchical Inheritance:

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

Example:

public class RegexMatches {
    public static void main(String args[]) {

        // String to be scanned to find the pattern.
        String line = "This order was placed for QT3000! OK?";
        String pattern = "(.*)(\\d+)(.*)";

        // Create a Pattern object
        Pattern r = Pattern.compile(pattern);

        // Now create matcher object.
        Matcher m = r.matcher(line);
        if (m.find()) {
            System.out.println("Found value: " + m.group(0));
            System.out.println("Found value: " + m.group(1));
            System.out.println("Found value: " + m.group(2));
        } else {
            System.out.println("NO MATCH");
        }
    }
}

Output:

meowing
eating

  • Multiple Inheritance (Through Interfaces):

In Multiple inheritance, one class can have more than one superclass and inherit features from all parent classes. Please note that Java does not support multiple inheritance with classes. In Java, we can achieve multiple inheritance only through Interfaces. In the image below, Class C is derived from interface A and B.

Multiple Inheritance in Java has always been a topic of debate among people.

So, java does not support multiple inheritance but this questions can be asked in other sense also, like:
If the question was: Can we extend more than one class, the answer is no.
If the question was: Can we inherit state and behavior from different classes, the answer is yes with polymorphism.

There are two methods explained in this post of doing multiple inheritance in java.

1. Using interface (see Method 1).
2. Also, there is another method do it (see Method 2)

Method 1:

InterfaceOne
package multiple_inheritance.method1;

public interface InterfaceOne {
	void showOne();
}
InterfaceTwo
package multiple_inheritance.method1;

public interface InterfaceTwo {
	void showTwo();
}
MultipleClass
package multiple_inheritance.method1;

public class MultipleClass implements InterfaceOne, InterfaceTwo{

	@Override
	public void showOne() {
		// TODO Auto-generated method stub
		System.out.println("override show One");
	}
	
	@Override
	public void showTwo() {
		// TODO Auto-generated method stub
		System.out.println("override show Two");
	}

}
MainClass
package multiple_inheritance.method1;

public class MainClass {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub

		MultipleClass multipleClass=new MultipleClass();
		multipleClass.showOne();
		multipleClass.showTwo();
	}

}
  • 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.

 

Find The Working Example Of Inheritance on codedbug GitHub Repo.