Types of Inheritance in Java
On the basis of class in Java, three types of inheritance is defined: Single, Multilevel and Hierarchical Inheritance
1. Single Inheritance:
When a class inherits another class, called single inheritance.
For example: Bike class inherits Vehicle class
class Vehicle {
int numberOfWheels;
String color;
public Vehicle(int noOfWheels, String color){
this.numberOfWheels = noOfWheels;
this.color = color;
}
public String getColor(){
return this.color;
}
}
class Bike extends Vehicle{
public Bike(int noOfWheels, String color){
super(noOfWheels, color);
}
}
2. Multilevel Inheritance:
When a class inherits another class which also inherits another class is called multiplevel inheritance. For example if a class C inherits class B and class B inherits class A
class A{
//properties and fields
}
class B extends A{
//properties of class B and its fields
}
class C extends B{
//properies of class C and its fields
}
3. Hierachical Inheritance:
When more than one classes inherit a single class, then this type of inheritance is called hierarchical inheritance.
class Vehicle {
int numberOfWheels;
String color;
public Vehicle(int noOfWheels, String color){
this.numberOfWheels = noOfWheels;
this.color = color;
}
public String getColor(){
return this.color;
}
}
class Bike extends Vehicle{
public Bike(int noOfWheels, String color){
super(noOfWheels, color);
}
}
class Car extends Vehicle{
boolean hasDisplayScreen = true;
public Car(int noOfWheels, String color){
super(noOfWheels, color);
}
Here Bike and Car both classes inherit Vehicle class, hence it is an example of hierarchical inheritance.
Note: Java does not support multiple inheritance for classes. To know why: click here
On the basis of interface- multiple and hybrid inheritance are defined.
Comments
Post a Comment