Java: Inheritance (IS-A)

Pre-requisite: Java: OOPS Concepts, Java: Class, Java: Object

Inheritance is a process where child class acquired all the properties and behaviors of the parent class. Inheritance is used when one object is based on another object. Here parent class also called a superclass and child class called a subclass.

For Example,  Person is Parent class and Employee is a subclass of Person. which acquired all the properties and behavior of Person class.

Advantage of inheritance

What is code Reusability in Inheritance?

Inheritance facilitates to reuse the fields and methods of the parent class in child class syntax of Java Inheritance.

Syntax of Inheritance Declaration

class Subclass-name extends Superclass-name  
{  
   //fields 
   //methods   
}

In java, extends keyword is used to inherit a class where a new class derived properties and methods of an existing class. The class that inherited is called a Parent/Superclass, and a new derived class is called a child/subclass.

What You Can Do in a Subclass?

A subclass inherits all of the public and protected members(fields, methods and nested classes) of its parent class, no matter what package the subclass is in. If the subclass is in the same package as its parent, it also inherits the private members of the parent class.

Constructors are not members of the class, so they are not inherited by child class, but the constructor of the parent class can be invoked from the child class by using super.

These inherited members can use as-is, replace them, hide them, or supplement them with new members:

  • Parent class inherited fields  can be used directly, just like any other class field.
  • You can declare a field in the child class with the same name as the one in the parent class, thus hiding it (not recommended).
  • You can declare new fields in the child class that are not in the parent class.
  • The inherited parent class methods can be used directly as they are.
  • You can write a methods in child class that has the same signature as the one in the parent class. i.e Method Overriding.
  • You can write a new static method in the child class with the same signature as on the parent class, thus hiding it.
  • You can declare new methods in the child class that are not in the parent class.
  • You can write a child class constructor that invokes the constructor of the parent class, either implicitly or by using the keyword super.

Example of Inheritance

In this example, Animal is a parent class which is extended by the Dog Child class. The animal class having properties name, breed, age and color. There is one method print() to print all these values. Dog subclass will inherit all these properties those having access modifiers as public and protected. Child class Dog print() method is calling parent class print() method by super keyword.

Java inheritance Example
Java Inheritance Example
//POJO Class
public class Animal {
	// private variables
	private String name;
	private String breed;
	private int age;
	private String color;

	// Getter and setter methods
	public Animal(String name, String breed, int age, String color) {
		this.name = name;
		this.breed = breed;
		this.age = age;
		this.color = color;
	}
    //Method of class
	public String print() {
		return "Animal [name=" + name + ", breed=" + breed + ", age=" + age + ", color=" + color + "]";
	}
}
public class Dog extends Animal {
	private String type;

	public Dog(String name, String breed, int age, String color, String type) {
		// call super class constructor to initialize
		super(name, breed, age, color);
		this.type = type;
	}

	// Overriding method of parent class
	@Override
	public String print() {
		return "Dog [type=" + type + ", print()=" + super.print() + "]";
	}
}
public class TestInheritance {

	public static void main(String[] args) {

		 //Instance with Parameterize Constructor
	     Animal dog=new Animal("Tommy","Small Dog",5,"Black");
	     //calling super class method because reference to super class
	     System.out.println(dog.print());

	     Animal dog_tiny=new Dog("Tiny","Small Dog",4,"Black","Bichon Friese");
	     //calling super class method because reference to super class
	     System.out.println(dog_tiny.print());

	     Dog dog_big=new Dog("Tufan","Big Dog",4,"White","Spotted");
	     //calling sub class method because reference to sub class
	     System.out.println(dog_big.print());
	}
}

Output


Animal [name=Tommy, breed=Small Dog, age=5, color=Black]
Dog [type=Bichon Friese, print()=Animal [name=Tiny, breed=Small Dog, age=4, color=Black]]
Dog [type=Spotted, print()=Animal [name=Tufan, breed=Big Dog, age=4, color=White]]

Here from this output, you will see the print method called based on object not by references of the object.

Points about Inheritance

  • extends the keyword used to implement inheritance.
  • Java doesn’t support multiple inheritances. It’s possible by implementing multiple interfaces.
  • Inheritance has an “IS-A” relationship.
  • Excepting Object Class, which has no parent class, every class has one and only one direct parent class (single inheritance). In the absence of any other explicit parent class, every class is implicitly a child class of Object.

Type of Inheritance in Java

Java supports three types of inheritance only for classes:

  1. Single
  2. Multi-Level
  3. HierarchicalJava Types Of Inheritance

Note:

  • Multiple Inheritance is not supported in java through the class.
  • Multiple and Hybrid inheritance is supported in java through interface only.

Single Level Inheritance

As you have seen in the above example is a single level of inheritance.

Multi-Level Inheritance

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

Output


Baby Dog Weepig...
Dog barking...
Animal eating...

Hierarchical Inheritance

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

Output


Cat meowing...
Animal eating...

Why multiple inheritance is not supported in java?

Java doen’t support multiple inheritance for class because of fixing ambiguity of common members like fields or method.

Suppose, we have three claases ClassA, ClassB and ClassC where ClassC extends ClassA and ClassB which are having common method display(). If you call display() method from child class then not sure which method got called because of ambiguity.
Since java not support multiple inheritance that’s why throgh compile time exception.

class ClassA{
void display(){System.out.println("Inside Class A");}
}
class ClassB{
void display(){System.out.println("Inside Class B");}
}
//Compile time issue issue here
class ClassC extends ClassA,ClassB{
 //suppose if it were
 public static void main(String args[]){
   ClassC obj=new ClassC();
   //Here it will through compile time issue
   obj.display();
}