Java Inheritance
Source: Dev.to
What is Inheritance?
Inheritance is a mechanism where one class gets the states and behaviors of another class.
It represents an is‑a relationship, meaning inheritance should be used only when such a relationship exists between two classes.
A child class (subclass) uses features of a parent class (superclass).
The extends keyword is used to perform inheritance in Java.
Superclass
public class Employee {
int employeeID;
int salary;
public static void main(String[] args) {
// entry point
}
public void work() {
System.out.println("Employee work");
}
}
Subclass
public class Developer extends Employee {
public static void main(String[] args) {
Developer d1 = new Developer();
d1.employeeID = 18426;
d1.salary = 400000;
System.out.println(d1.employeeID);
System.out.println(d1.salary);
d1.work();
d1.devWork();
}
public void devWork() {
System.out.println("Coding");
}
}
Benefits of Inheritance
- Code reuse
- Avoid duplication
- Easier maintenance
- Builds relationships between classes
Types of Inheritance
- Single Inheritance
- Multilevel Inheritance
- Hierarchical Inheritance
- Multiple Inheritance
- Hybrid Inheritance