Pages

Thursday, August 13, 2020

Inheritance in Java, Inheritance Types with Examples

1. Inheritance in Java:

We will guide you to learn what is Inheritance in Java with examples, What are the Types of Inheritance, What is the significance of super keyword in it, Advantages, Disadvantageous. .

Inheritance is one of the core principle of OOPS concepts. Inheritance provides the facility to acquire one class properties such as instance variables and methods by another class.


In Java, It is impossible to write a class without using Inheritance concept. Every class by default inherits the fields and method of Object class.


Inheritance in Java, Inheritance Types with Examples



2. Default Object class in Inheritance:

First, Let us see a simple program that gets the methods from Object class.

package blog.java.w3schools.inheritance;

public class InheritanceDefault {

 public static void main(String[] args) {

  InheritanceDefault obj1 = new InheritanceDefault();
  InheritanceDefault obj2 = new InheritanceDefault();
  boolean isEquals = obj1.equals(obj2);
  System.out.println("obj1 is equal to obj2 : " + isEquals);
 }
}



Output:


obj1 is equal to obj2 : false

The above program compiles and runs successfully. In fact, InheritanceDefault class does not have equals method but obj1 had invoked equals method.

3. Where did that equals come from?


Answer is equals method from Object class.


3.1 Object class and its methods in Java


As stated above, every class has access to all methods of Object class in java by default. Object has many methods like equals, toString, notify, wait etc.


Extends Keyword:


extends is a keyword in java which is used to inherit the properties of another class.

Syntax:


class SuperClass
{
 // some code here
}

class SubClass extends SuperClass
{
 // some code here
}


See how extends keyword is used in polymorphism. 



3.2 Inheritance Example Program:


We will take two classes now MiniCalculator and MainCalculator classes for demonstration. This program is how to write Calculator program in Java using Inheritance concept.

Below is the best example for parent and child class relationship.


package blog.java.w3schools.inheritance;

class MiniCalculator {
 public int sumTwo(int a, int b) {
  return a + b;
 }

 public int substractionTwo(int a, int b) {
  return a - b;
 }
}

public class MainCalculator extends MiniCalculator {
 public static void main(String[] args) {

  MainCalculator calculator = new MainCalculator();
  System.out.println("Sum of two numbers: " + calculator.sumTwo(10, 20));
  System.out.println("Substraction of two numbers: " + calculator.sumTwo(30, 20));
  System.out.println("Division of two numbers: " + calculator.sumTwo(40, 20));
  System.out.println("Multiplication of two numbers: " + calculator.sumTwo(100, 20));
 }

 public int multiplyTwo(int a, int b) {
  return a * b;
 }

 public int divisionTwo(int a, int b) {
  return a / b;
 }
}

Output:



Sum of two numbers: 30
Substraction of two numbers: 50
Division of two numbers: 60
Multiplication of two numbers: 120


Please observe the class MiniCalculator has two methods and they are sumTwo, substractionTwo.

Class MainCalculator has another two different methods multiplyTwo, divisionTwo.

Created an object for class MainCalculator and accessed four methods but MainCalculator has only two methods. So where did those two methods have come from?

See the class MainCalculator declaration has extends keyword for MiniClaculator class. so methods available in this class directly accessible in MainCalculator. This is the power of Inheritance for code re-usability. MiniCalculator can be used by any other classes by extending it.


4. Types Of Inheritance:


Inheritance can be implemented in 5 ways and below are types that comes from OOPS concepts.

1) Single Inheritance
2) Multi-Level Inheritance
3) Multiple Inheritance
4) Hierarchical Inheritance
5) Hybrid Inheritance



4.1 Single Inheritance: 

This is very easy to understand. If a class extends only one class then it is called as Single Inheritance. Look at the below diagram where class B extends class A.

Here always only one base class and one child class.
Single_Inheritance


package blog.java.w3schools.inheritance;

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

  A a = new A();
  a.printA();

  B b = new B();
  b.printA();
  b.printB();
 }
}

class A {
 public void printA() {
  System.out.println("PrintA method.");
 }
}

class B extends A {
 public void printB() {
  System.out.println("PrintB method.");
 }
}


Output:


PrintA method.
PrintA method.
PrintB method.

Through object A, we can call only class A methods. But, both methods can be invoked using B object. Because class B is inheriting class A properties and methods.


4.2 Multi-Level Inheritance:


If a class is derived from another child or derived class is said to be "Multi-Level Inheritance". Derived class means a child class.
This can be minimum of three or more classes involve in this type of inheritance. For example, class B inherits class A and class C inherits class B.


Multi-Level Inheritance



package blog.java.w3schools.inheritance;

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

  C c = new C();
  c.printA();
  c.printB();
  c.printC();
 }
}

class A {
 public void printA() {
  System.out.println("PrintA method.");
 }
}

class B extends A {
 public void printB() {
  System.out.println("PrintB method.");
 }
}

class C extends B {
 public void printC() {
  System.out.println("PrintC method.");
 }
}

Output:



PrintA method.
PrintB method.
PrintC method.


Observe carefully, all three methods can be invoked by object c. This is the power of inheritance.


4.3 Multiple Inheritance:


Multiple Inheritance is when one class inherits multiple classes at a time. Basically, Java does not support Multiple Inheritance.
This is not much implemented any real time projects and not supported in many OO programming languages such as Small Talk, Java, C# do not support Multiple inheritance. Only one language supports Multiple Inheritance is C++.





Multiple_Inheritance



The main problem is that if both parent classes have a same method then child class which method of parent class will be accessed. This makes ambiguity to the compiler and leads to diamond problem. To avoid all these circumstances, java not supporting it.


4.4 Hierarchical Inheritance:


In simple terms, one base class - multiple child classes. A base class is inherited by many classes(child). Take a look at the below diagram.




Hierarchical_Inheritance


Class A is a base class.
Class B inherits class A
Class C inherits class A
Class D inherits class A

class B, C, D are inherited class A.


package blog.java.w3schools.inheritance;

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

  B b = new B();
  b.printA();
  b.printB();

  System.out.println("--------------");

  C c = new C();
  c.printA();
  c.printC();

  System.out.println("--------------");

  D d = new D();
  c.printA();
  c.printC();
 }
}

class A {
 public void printA() {
  System.out.println("PrintA method.");
 }
}

class B extends A {
 public void printB() {
  System.out.println("PrintB method.");
 }
}

class C extends A {
 public void printC() {
  System.out.println("PrintC method.");
 }
}

class D extends A {
 public void printD() {
  System.out.println("PrintD method.");
 }
}

Output:




PrintA method.
PrintB method.
--------------
PrintA method.
PrintC method.
--------------
PrintA method.
PrintC method.
 



Class B, C, D objects are able to call class A method directly without creating object for class A.

 

4.5 Hybrid Inheritance:


Hybrid Inheritance is combination of any two or more inheritances together. It may be single and multi level inheritance or multi-level or Hierarchical inheritance.

In this combination, we should not use multiple inheritance which is not supported by Java.



Hybrid_Inheritance



Hybrid_Inheritance_java
Interview Question on Inheritance.

5. Super Keyword in Inheritance:


Super keyword prominently used to call super class methods if the method exists in child class same as super class.

Thumb rule to super is super keyword always refers to super class, not related from where it is being invoked.


package blog.java.w3schools.super;

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

  B b = new B();
  b.print();
 }
}

class A {
 public void print() {
  System.out.println("A Print method.");
 }
}

class B extends A {
 public void print() {
  super.print(); // calling its super class print method.
  System.out.println("B Print method.");
 }
}


Output:





A Print method.
B Print method.



6. HAS-A and IS-A Relationship:


Java IS-A and HAS-A Relationship plays a significant role in all applications.
HAS-A relationship is declared with "extends" keyword and helpful when all functionalities are need in sub-classes. This handled by the java compiler with intelligence.
Where as IS-A Relationship is not declared with any keyword but it comes into reality when use a instance variable to another class which has some common functionalities. You can see that only one method is used in IS-A relationship examples.

Full article on HAS-A and IS-A Relationship.


7. Inheritance Advantages:


1) Reduce code redundancy.
2) Efficient code re-usability.
3) Reduces source code size and improves code readability.
4) Easy to manage
5) Supports application code extensible by overriding the base class functionality within child classes.


8. Inheritance Disadvantages:


1) In Inheritance, base class and child classes are tightly coupled. Hence If you change the code of parent class, it will get affects to the all the child classes.

2) All unused data members are loaded into memory. It may impact application performance.

9. Summary:

Inheritance is used to acquire one class properties such as instance variables and methods by another class. By default, every class inherits Object class. Inheritance types are Single, Multi-Level, Multiple, Hierarchical, Hybrid Inheritance. Super keyword is to invoke super class methods from sub-class.



1 comment:

Please do not add any spam links in the comments section.