Inheritance
Java Inheritance is a fundamental concept in OOP(Object-Oriented Programming). It is the mechanism in Java by which one class is allowed to inherit the features(fields and methods) of another class. In Java, Inheritance means creating new classes based on existing ones. A class that inherits from another class can reuse the methods and fields of that class.
Example: In the following example, Animal is the base class and Dog, Cat and Cow are derived classes that extend the Animal class.
Types of Inheritance in Java
Single Inheritance
Multilevel Inheritance
Hierarchical Inheritance
Multiple Inheritance
Hybrid Inheritance
In single inheritance, a sub-class is derived from only one super class. It inherits the properties and behavior of a single-parent class. Sometimes, it is also known as simple inheritance.
Examples program:
//parent class
class Animal {
void eat() {
System.out.println("This animal can eat");
}
}
// child class
class Dog extends Animal {
void bark() {
System.out.println("Barks");
}
}
public class Single {
public static void main(String[] args) {
Dog d = new Dog();
d.bark();
d.eat();
}
}
OUTPUT:
Barks
This animal can eat
2) Multilevel Inheritance
In Multilevel Inheritance, a derived class will be inheriting a base class and as well as the derived class also acts as the base class for other classes.
Examples program
class Cricket {
void Game() {
System.out.println("This is game of Cricket ");
}
}
class Batsman extends Cricket {
void Batsman() {
System.out.println("I am a Batsman, my role score runs");
}
}
class AllRounder extends Batsman {
void AllRounder() {
System.out.println("I am a AllRounder, I can Bat and Bowl");
}
}
public class Multilevel{
public static void main(String[] args) {
AllRounder player = new AllRounder();
player.Game();
player.Batsman();
player.AllRounder();
}
}
OUTPUT :
This is game of Cricket
I am a Batsman, my role score runs
I am a AllRounder, I can Bat and Bowl
3) Hierarchical Inheritance
In hierarchical inheritance, more than one subclass is inherited from a single base class. i.e. more than one derived class is created from a single base class. For example, cars and buses both are vehicle
Examples program:
// Parent class
class Sports {
void play() {
System.out.println("Playing a Sport");
}
}
// Child class 1
class Cricket extends Sports {
void cricketRules() {
System.out.println("Cricket is played with bat and ball, 11 players in each team");
}
}
// Child class 2
class Kabaddi extends Sports {
void kabaddiRules() {
System.out.println("Kabaddi is played by raiding and defending, 7 players in each team");
}
}
public class Hierarchical {
public static void main(String[] args) {
Cricket c = new Cricket();
c.play();
c.cricketRules();
Kabaddi k = new Kabaddi();
k.play();
k.kabaddiRules();
}
}
OUTPUT:
Playing a Sport
Cricket is played with bat and ball, 11 players in each team
Playing a Sport
Kabaddi is played by raiding and defending, 7 players in each team
Top comments (0)