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

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.



COMMENTS

BLOGGER: 1
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,37,ArrayList,18,Arrays,24,Bean Creation,3,Bean Scopes,1,BiConsumer,1,Blogger Tips,1,Books,1,C Programming,1,Collection,8,Collections,37,Collector,1,Command Line,1,Comparator,1,Compile Errors,1,Configurations,7,Constants,1,Control Statements,8,Conversions,6,Core Java,149,Corona India,1,Create,2,CSS,1,Date,3,Date Time API,38,Dictionary,1,Difference,2,Download,1,Eclipse,3,Efficiently,1,Error,1,Errors,1,Exceptions,8,Fast,1,Files,17,Float,1,Font,1,Form,1,Freshers,1,Function,3,Functional Interface,2,Garbage Collector,1,Generics,4,Git,9,Grant,1,Grep,1,HashMap,2,HomeBrew,2,HTML,2,HttpClient,2,Immutable,1,Installation,1,Interview Questions,6,Iterate,2,Jackson API,3,Java,32,Java 10,1,Java 11,6,Java 12,5,Java 13,2,Java 14,2,Java 8,128,Java 8 Difference,2,Java 8 Stream Conversions,4,java 8 Stream Examples,12,Java 9,1,Java Conversions,14,Java Design Patterns,1,Java Files,1,Java Program,3,Java Programs,114,Java Spark,1,java.lang,4,java.util. function,1,JavaScript,1,jQuery,1,Kotlin,11,Kotlin Conversions,6,Kotlin Programs,10,Lambda,2,lang,29,Leap Year,1,live updates,1,LocalDate,1,Logging,1,Mac OS,3,Math,1,Matrix,6,Maven,1,Method References,1,Mockito,1,MongoDB,3,New Features,1,Operations,1,Optional,6,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,2,Sort,1,Sorting Techniques,8,Spring,2,Spring Boot,23,Spring Email,1,Spring MVC,1,Streams,31,String,61,String Programs,28,String Revese,1,StringBuilder,1,Swing,1,System,1,Tags,1,Threads,11,Tomcat,1,Tomcat 8,1,Troubleshoot,26,Unix,3,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://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi7Pt6o6h7t_KPTdKhiHwnFR35YxY_q0PBHMTTwUsrl4LlkCXkHXIGxge0zHYbpxigR4KS7DPosYs9cv5GeDfSzqeiaEEsc21NuDLfHK3Scb9D1NTVWGOLDEMGGhcJ9lOFu5-wY8mbxx9E/w640-h373/21+java-inheritance.jpg
https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi7Pt6o6h7t_KPTdKhiHwnFR35YxY_q0PBHMTTwUsrl4LlkCXkHXIGxge0zHYbpxigR4KS7DPosYs9cv5GeDfSzqeiaEEsc21NuDLfHK3Scb9D1NTVWGOLDEMGGhcJ9lOFu5-wY8mbxx9E/s72-w640-c-h373/21+java-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