Java Inheritance Introduction

It is the concept of OOPs (object oriented programming). Inheritance allow us to inherit the features of base class(super class).

Use of inheritance

class It contains group of objects.

subclass(child class) It inherit from base class /superclass.

superclass(parent class) subclass inherits from super class also called base class/parent class.

Inheritance Syntax

class child_class_name extends parent_class_name  
   //methods and fields  

Types of Inheritance

Single Inheritance:

In Single Inheritance only one class extends another class .

Single Inheritance Example

class SingleInheritance{ 
	static int num1=10; 
	static int num2=5; 
class MainInheritance extends SingleInheritance{ 
	public static void main(String[] args){ 
	int num3=2; 
	int result=num1+num2+num3; 
	System.out.println("Result of child class is "+result); 

Result of child class is 17

Java Multiple Inheritance:

In Multiple Inheritance, one class extending more than one class. Java does not support multiple inheritance.

Java Multiple Inheritance Example

package com.inheritance; 

interface Car 
    int  speed=60; 
    public void distanceTravelled(); 
interface Bus 
    int distance=100; 
    public void speed(); 
public class Vehicle  implements Car,Bus 
    int distanceTravelled; 
    int averageSpeed; 
    public void distanceTravelled() 
        System.out.println("Total Distance Travelled is : "+distanceTravelled); 
    public void speed() 
        int averageSpeed=distanceTravelled/speed; 
        System.out.println("Average Speed maintained is : "+averageSpeed); 
    public static void main(String args[]) 
        Vehicle v1=new Vehicle(); 

Total Distance Travelled is : 6000
Average Speed maintained is : 100

Java Multilevel Inheritance:

In Multilevel Inheritance, one class can inherit from a derived class. Hence, the derived class becomes the base class for the new class.

Java Multilevel Inheritance Example

class MultilevelInheritance{ 
	protected String str; 
	MultilevelInheritance() {
		str = "This "; 
class ChildClass1 extends MultilevelInheritance { 
	ChildClass1() { 
		str = str.concat("is "); 
class ChildClass2 extends ChildClass1 { 
	ChildClass2() { 
		str = str.concat("Multilevel Inheritance "); 
class ChildClass3 extends ChildClass2 { 
	ChildClass3() { 
		str = str.concat("Example."); 
	void display() { 
class MultilevelInheritanceMain { 
	public static void main(String args[]) { 
		ChildClass3 obj = new ChildClass3(); 

This is Multilevel Inheritance Example.

Java Hierarchical Inheritance:

In Hierarchical Inheritance, one class is inherited by many sub classes.

Hybrid Inheritance:

Hybrid inheritance is a combination of Single and Multiple inheritance.

© copyright 2017-2022 Completedone pvt ltd.