Inheritance In Java With Real Time Example And Diagrams

Inheritance is one of the basic fundamental concepts of OOP’s.  Inheritance represents the IS-A relationship between the objects which is also known as a parent-child relationship. Some more points are listed below,

  • The process by which one class acquires the properties (data members) and functionalities (methods) of another class is called inheritance.
  • The code that is already present in base class need not be rewritten in the child class.
  • The inheritance mechanism is very useful in code reuse.
  • A class which is inherited is called a Base Class / Parent class / Super class. The classes which are inheriting Base classes are called Child class / Sub class.
  • In Java, A subclass can have only one Parent class, whereas a Parent class may have one or more Child classes. Because Java doesn’t support multiple inheritance.
  • The meaning of “extends” is to increase the functionality.

Important points on Inheritance

What is inheritance?

Inheritance which allows a class to inherit behavior and data from other class. In other word inheritance is a mechanism wherein a new class is derived from an existing class.

Types of Inheritance

  • Single inheritance
  • Multiple inheritance
  • Hierarchical inheritance
  • Multilevel inheritance
  • Hybrid inheritance
Inheritance, OOPs concept in java programming language, Inheritance in java, Types of inheritance in java

What is the primary benefit of inheritance?

  • Code reusability and reduces duplicate code.
  • It makes code more flexible.
  • It takes less time for application development and execution.
  • Memory consumption is less and performance will be improved.
  • Since less number of code, storage cost will be reduced.

Example1

class Parentclass
{
//Data and methods
}

class Childclass extends Parentclass 
{
//Data and methods
}

  Example2

//Base class
class Vehicle{	
	public int gear;
	public int speed;
	
	public Vehicle(int gear, int speed){	
	this.gear = gear;
	this.speed= speed;	
	}

	public String display(){		
		return ("Gear is: "+ gear +" and the speed is: "+speed);		
	}	
}

//Derived Class
class PulsarBike extends Vehicle {
	public int NoOfWheels;	
	public PulsarBike(int gear, int speed, int wheel) {
		super(gear, speed);
		NoOfWheels = wheel;
	}
	
	//Overridding 
	public String display(){
		return ("Gear is "+ gear +", speed is "+speed+ " and noOfWheel is: "+NoOfWheels);		
	}
}

public class Inheritance {
	public static void main(String[] args) {		
		PulsarBike pule = new PulsarBike(5, 60, 2);
		System.out.println(pule.display());
		
	}
}

Output:
Gear is 5, speed is 60 and noOfWheel is: 2

Recommended post in OOPs concept:

Leave a Comment

Your email address will not be published.