$show=/label

Inheritance in Java, Inheritance Types with Examples

SHARE:

Inheritance in Java, Inheritance Types with Examples, Inheritance provides the facility to acquire one class properties such as instance variables and methods by another class.

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.


java-inheritance



Default Object class in Inheritance:



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.

Where did that equals come from?


Answer is equals method from Object class.


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. 



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.


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.


Types Of Inheritance:


There are 5 types of inheritance.

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



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.


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.


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) 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.

 

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.

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.



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.


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.


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.

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.

COMMENTS

BLOGGER: 2
  1. And indeed, I’m just always astounded concerning the remarkable things served by you. Some four facts on this page are undeniably the most effective I’ve had.
    Surya Informatics

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

About Us

Author: Venkatesh - I love to learn and share the technical stuff.
Name

accumulo,1,ActiveMQ,2,Adsense,1,API,31,ArrayList,16,Arrays,2,Bean Creation,3,Bean Scopes,1,BiConsumer,1,Blogger Tips,1,Books,1,C Programming,1,Collection,4,Collections,20,Collector,1,Command Line,1,Compile Errors,1,Configurations,7,Constants,1,Control Statements,8,Conversions,5,Core Java,72,Corona India,1,Create,2,CSS,1,Date,2,Date Time API,3,Dictionary,1,Difference,1,Download,1,Eclipse,2,Efficiently,1,Error,1,Errors,1,Exception,1,Exceptions,2,Fast,1,Files,9,Float,1,Font,1,For examples,1,For loop examples,1,For Loop in Java,1,Form,1,Freshers,1,Function,3,Functional Interface,2,Garbage Collector,1,Generics,4,Git,4,Grant,1,Grep,1,HashMap,1,HomeBrew,2,HTML,2,HttpClient,2,Immutable,1,Inner for loops,1,Installation,1,Interview Questions,5,Iterate,2,Jackson API,3,Java,28,Java 10,1,Java 11,5,Java 12,5,Java 13,2,Java 14,2,java 5 For loop,1,Java 8,48,Java 9,1,Java Design Patterns,1,Java Files,1,Java for loop,1,Java Program,2,Java Programs,65,java.lang,5,java.util. function,1,jQuery,1,Kotlin,10,Kotlin Programs,6,Lambda,1,lang,29,Leap Year,1,live updates,1,Mac OS,2,Math,1,Maven,1,Method References,1,Mockito,1,MongoDB,3,Nested for loop,1,Nested for loop examples,1,New Features,1,Operations,1,Optional,4,Oracle,5,Oracle 18C,1,Partition,1,Patterns,1,Programs,1,Property,1,Python,2,Quarkus,1,Read,1,Real Time,1,Recursion,2,Remove,2,Rest API,1,Schedules,1,Serialization,1,Servlet,1,Sorting Techniques,8,Spring,2,Spring Boot,23,Spring Email,1,Spring MVC,1,Stream,3,Streams,11,String,48,String Programs,8,String Revese,1,Swing,1,System,1,Tags,1,Threads,8,Tomcat,1,Tomcat 8,1,Troubleshoot,16,Unix,2,Updates,3,util,5,While Loop,1,
ltr
item
JavaProgramTo.com: Inheritance in Java, Inheritance Types with Examples
Inheritance in Java, Inheritance Types with Examples
Inheritance in Java, Inheritance Types with Examples, Inheritance provides the facility to acquire one class properties such as instance variables and methods by another class.
https://2.bp.blogspot.com/-siemDqUrN4Y/WhR94c-whEI/AAAAAAAAA6g/biKWACnuzcYzRSSuW1b7h0w_LmjEWwHxgCLcBGAs/s400/21%2Bjava-inheritance.jpg
https://2.bp.blogspot.com/-siemDqUrN4Y/WhR94c-whEI/AAAAAAAAA6g/biKWACnuzcYzRSSuW1b7h0w_LmjEWwHxgCLcBGAs/s72-c/21%2Bjava-inheritance.jpg
JavaProgramTo.com
https://www.javaprogramto.com/2017/11/java-inheritance.html
https://www.javaprogramto.com/
https://www.javaprogramto.com/
https://www.javaprogramto.com/2017/11/java-inheritance.html
true
3124782013468838591
UTF-8
Loaded All Posts Not found any posts VIEW ALL Readmore Reply Cancel reply Delete By Home PAGES POSTS View All RECOMMENDED FOR YOU LABEL ARCHIVE SEARCH ALL POSTS Not found any post match with your request Back Home Sunday Monday Tuesday Wednesday Thursday Friday Saturday Sun Mon Tue Wed Thu Fri Sat January February March April May June July August September October November December Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec just now 1 minute ago $$1$$ minutes ago 1 hour ago $$1$$ hours ago Yesterday $$1$$ days ago $$1$$ weeks ago more than 5 weeks ago Followers Follow THIS PREMIUM CONTENT IS LOCKED STEP 1: Share to a social network STEP 2: Click the link on your social network Copy All Code Select All Code All codes were copied to your clipboard Can not copy the codes / texts, please press [CTRL]+[C] (or CMD+C with Mac) to copy Table of Content