Inheritance in Java

Inheritance is the process where the characteristics are inherited from ancestors (super classes). Inheritance in java can be defined as a mechanism where a new class (subclass) is derived from an existing class(super class) properties.

It is possible for classes to inherit or acquire the properties and methods of other classes, just like a son can acquire some traits and behavior from his father.

In Java inheritance is declared using the extends keyword. You can declare that one class extends another class by using the keyword extends in the class definition


extends keyword used for Class to Class relationship.
extends keyword used for interface to interface relationship
implements keyword used with Interface to class interface

Child Class / Sub Class : The class that extends the features of another class is known as child class, sub class or derived class.

Parent Class / Super class : The class whose properties and functionalities are used(inherited) by another class is known as parent class, super class or Base class.

Important things in Inheritance

  • Most important benefit of inheritance is code reuse because subclasses inherit the variables and methods of superclass.
  • Private members of superclass are not directly accessible to subclass, as private members' scope is only the particular class where they are declared.
  • Superclass members with default access is accessible to subclass only if they are in same package,. Default access is nothing but the state where you donot specify Public, Private, Protected.
  • Constructors are not inherited by subclasses.
  • We can override the method of Superclass in the Subclass, this most important when you inherit a interface
  • If a class is Final then we cannot inherit that class.

Types of inheritance :

There are four types of inheritance in java, those are :

  1. Single Inheritance
  2. Multi-level Inheritance
  3. Multiple Inheritance
  4. Hybrid Inheritance

Single Inheritance :

When a single child class inherits the properties of a parent class, it is known as single inheritance. There are no other child classes present for that parent class. single-inheritance-java


package cherchertech;
class BaseClass {
	public void testa() {
		System.out.println("test a");
	}
	public void testb() {
		System.out.println("test b");
	}
}
class ChildClass extends BaseClass{
	public void testc() {
		System.out.println("test c");
	}
}
public class SingleInheritance {
	public static void main(String[] args) {
		ChildClass cc = new ChildClass();
		// methods present in base class
		cc.testa();
		cc.testb();
		// method present in child class
		cc.testc();
	}
}
			
single-inheritance-java-output

Multi-level Inheritance :

When a class extends a class, which extends another class then it is called multilevel inheritance.

Multilevel inheritance is nothing but the combination of more than one single inheritance

In multiple inheritance you have one path only to reach the highest class in the inheritance.

Minimum three classes are required to achieve the Multi-level inheritance in java.


The last sub class will have all the properties present in its super classes.

In below example you have only one path to reach from last sub class to top most class, Grand child class -> Child Class -> Base class


package cherchertech;
class BaseClass {
	public void testa() {
		System.out.println("Base class test");
	}
}
class ChildClass extends BaseClass{
	public void testb() {
		System.out.println("Child class test");
	}
}
class GrandChildClass extends ChildClass{
	public void testc() {
		System.out.println("Grand child class");
	}
}
public class MultiLevelInheritance {
	public static void main(String[] args) {
		GrandChildClass gc = new GrandChildClass();
		// method present in base class
		gc.testa();
		// method present in child class
		gc.testb();
		// method present in grand child class
		gc.testc();
	}
}
			
multilevel-inheritance-java

Multiple Inheritance :

Multiple inheritance is nothing but a class/interface is inheriting the properties of more than one class or interface.

A class cannot inherit the more than one class because it forms multiple paths to reach the top most class from the same last sub class.

This is where you need to remember that all the classes in java are subclasses to Object class.

So Multiple inheritance is not possible when a class tries to inherit more than one class, if class tries so, then it creates a diamond problem.

But a class can inherit one class and implement multiple interfaces and this is also called as multiple inheritance.

Similar to this Interfaces also can inherit from more than one interface, java allows multiple inheritance only because interfaces will not have any implementations

multple-inheritance-java

Hybrid Inheritance :

Hybrid inheritance is the combination of every type of inheritance that exist. As java doesn't support multiple inheritance, hybrid inheritance also can't be implemented.

If you consider the above definition then Hybrid inheritance is not possible

For most of the java people the Hybrid inheritance definition is : Combination of Single level and Multilevel inheritance.

Other way of saying : When two classes inherit properties from a single class then it is called Hybrid inheritance.

hybrid-inheritance-java


package cherchertech;
class BaseClass {
	public void testa() {
		System.out.println("Base class test");
	}
}
class Child_1_Class extends BaseClass{
	public void testb() {
		System.out.println("Child 1 class test");
	}
}
class Child_2_Class extends BaseClass{
	public void testd() {
		System.out.println("Child 2 class test");
	}
}
class GrandChildClass extends Child_1_Class{
	public void testc() {
		System.out.println("Grand child class test");
	}
}
public class HybridInheritance {
	public static void main(String[] args) {
		GrandChildClass gc = new GrandChildClass();
		// method present in base class
		gc.testa();
		// method present in child 1 class
		gc.testb();
		// method present in grand child class
		gc.testc();
		
		// create object child class 2
		Child_2_Class c2c = new Child_2_Class();
		// method present in child 2 class
		c2c.testd();
	}
}
			
hybrid-inheritance-output-java

Diamond problem and Why Java Does not have it :


diamond-problem-multiple-inheritance-java

The above image shows the diamond problem, let me explain the problem.

1. Class A extends Object class
2. Class B extends Object class
3. Class C extends Class A and class B.
4. Object class has methods called toString().
5. The relation between class C and classes A, B is Multiple inheritance
5. Classes A, B, C have method toString(), because they inherit the Object class

Lets create object for class C and call the toString() method, which indrectly gives call to toString() method present in the Object class.

Now take moment and think, In how many ways we can reach the Object class from the class C, yes Your are right, in two ways we can reach it.

1. Class C -> Class A -> Object class
2. Class C -> Class B -> Object class

Take a moment and think which is the way you are gonna use, Path 1 or Path 2 (consider you donot know the consequences of the path, good or bad).

Are you able to come to conclusion ? No, okay now the same thing happens with the Programming language as well, it gets confused which path to choose like Mr.Nobody movie, the Programming language will throw an exception of ambiguity.

To avoid this java Programming language author a made decision not to include the multiple inheritance. So we donot have Multiple inheritance between the classes.

In My language : There are two section of school students, among them each section has a student with roll number 1224, If principal asks an attender to call a guy (one guy) with roll number 1224, whom does that attender will call ?, he cannot call any body as there are two guys with same roll number, unless he is stupid like me.

Upcasting :

Upcasting is casting a subtype to a supertype, upward to the inheritance tree. In other words, Making a child or grand child as the grand father.

While creating a Object to a child class we will write Parent class type as the type for the object.

We can mention the the type to which '(A)' we are going to Upcast the object.


A a = (A) new B(); // where B is sub class of A			

Once we upcast the sub class then only methods from the Super class is available for that object.

But if a sub class has any method which is same as Superclass method then super class method will be overridden by the sub class and sub-class method implementation only will work.


class A {
	public void test(){
		System.out.println("test A");
	}
	public void subtract(){
		System.out.println("subtract A");
	}
}
class B extends A{
	public void test(){
		System.out.println("test B");
	}
	public void add(){
		System.out.println("add B");
	}
}
public class C {
	public static void main(String[] args) {
		A a =(A) new B();
		a.subtract();
		a.test();
	}
}			

Output of the up-casting program


subtract A
test B			

We donot have subclass method in suggestions as well. upcasting-java

Auto-Upcasting :

Auto-upcasting is nothing but the upcasting occurs automatically by the compiler, we can write the above example's object creation like below


A a = new B();			

Down casting

Down casting is nothing but converting the sub class type which is upcasted to Super class into sub class type, instead of performing the down casting we can directly create the object to sub class.

For creating a down casting process, Upcasting is mandatory.

For above Upcasting example:


A a = new B(); // auto-upcasting
B b =(B) new B(); // downcasting
"Donot you think instead of writing above two steps, we can write like below"
B b = new B();		

About Author

Myself KarthiQ, I am the author of this blog, I know ways to write a good article but some how I donot have the skills to make it to reach people, would you like help me to reach more people By sharing this Article in the social media.

Share this Article Facebook
Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions

Recent Addition

new tutorial Protractor Online Training : We have closed registration for training

Please do email to chercher.tech@gmail.com for any queries

If you already registered then please do check your email for the Webex link for the training starting from 15th Nov 2018
 
Join My Facebook Group
Join Group