This content originally appeared on DEV Community and was authored by Rajan S
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
types of inheritance
Single Inheritance
Multilevel Inheritance
Hierarchical Inheritance
Multiple Inheritance
Hybrid Inheritance
- Single Inheritance
class vehicle{
void bike()
{
System.out.println("bike comfort for two person");
}
}
class car extends vehicle {
void red()
{
System.out.println("car comfort for four person");
}
}
public class Single {
public static void main(String args[]) {
car c1 = new car ();
c1.bike();
c1.red();
}
}
Output
bike comfort for two person
car comfort for four person
- Multilevel Inheritance
class vehicle{
void bike()
{
System.out.println("bike comfort for two person");
}
}
class car extends vehicle {
void red()
{
System.out.println("car comfort for four person");
}
}
class bicycle extends car {
void black ()
{
System.out.println("i like so much");
}
}
public class Multilevel {
public static void main(String args[]) {
bicycle b1 = new bicycle();
b1.bike();
b1.red();
b1.black();
}
}
output
bike comfort for two person
car comfort for four person
i like so much
- Hierarchical Inheritance
class vehicle{
void bike()
{
System.out.println("bike comfort for two person");
}
}
class car extends vehicle {
void red()
{
System.out.println("car comfort for four person");
}
}
class van extends car {
void white ()
{
System.out.println("van comfort in more person");
}
}
public class Hierarchical {
public static void main(String args[]) {
van v1 = new van();
v1.bike();
v1.red();
v1.white();
}
}
output
bike comfort for two person
car comfort for four person
van comfort in more person
This content originally appeared on DEV Community and was authored by Rajan S