INHERITANCE
Inheritance is one of the main ideas in Object-Oriented Programming (OOP).
It allows one class to use the properties and methods of another class.
In simple terms, Inheritance means creating a new class from an existing class.
The new class (called the child class) can use the fields and methods of the old class (called the parent class).
Example: Animal is the base class and Dog, Cat and Cow are derived classes that extend the Animal class
Types of inheritance
- Single Inheritance
- Multilevel Inheritance
- Hierarchical Inheritance
- Multiple Inheritance
- Hybrid Inheritance
SINGLE 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
For example :
//Super class
class Father {
void work() {
System.out.println("Father is working hard");
}
}
// Subclass
class Son extends Father {
void play() {
System.out.println("Son is playing friends");
}
}
public class Single1 {
public static void main(String[] args) {
Son s = new Son();
s.work();
s.play();
}
}
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.
For example
class CEO {
void showCEO() {
System.out.println("I am the CEO of the company");
}
}
class Manager extends CEO {
void showManager() {
System.out.println("I am the Manager under the CEO");
}
}
class Employee extends Manager {
void showEmployee() {
System.out.println("I am the Employee working under the Manager");
}
}
public class Multilevel{
public static void main(String[] args) {
Employee emp = new Employee();
emp.showCEO();
emp.showManager();
emp.showEmployee();
}
}
HIERARCHICAL INHERITANCE
In hierarchical inheritance, more than one subclass is inherited from a single base class more than one derived class is created from a single base class. For example, Mobile,Brand and Ram
For example
class Mobile {
void mobileDetails() {
System.out.println("This is a Mobile Device");
}
}
class Brand extends Mobile {
void brandName() {
System.out.println("Brand nothing");
}
}
class Ram extends Mobile {
void ramSize() {
System.out.println("RAM 8GB");
}
}
public class Hierarchical {
public static void main(String[] args) {
Brand b = new Brand();
b.mobileDetails();
b.brandName();
System.out.println();
Ram r = new Ram();
r.mobileDetails();
r.ramSize();
}
}
Top comments (0)