Java Inheritance
Java inheritance is one of the most important concepts of Object-Oriented Programming (OOP). It allows one class to inherit the properties and methods of another class. By using inheritance, developers can reuse existing code, reduce duplication, and create a logical relationship between classes.
In Java, inheritance is implemented using the extends keyword. The class that inherits another class is called the child class (subclass), while the class being inherited is called the parent class (superclass).
What is Inheritance in Java?
Inheritance is a mechanism where one class acquires the fields and methods of another class. The child class can use all accessible members of the parent class and can also define its own additional properties and methods.
Syntax of Java Inheritance
class Parent{
}
class Child extends Parent{
}
Java Inheritance Example
class Animal{
void sound() {
System.out.println("Animal makes sound");
}
}
classDog extends Animal {
void bark() {
System.out.println("Dog barks");
}
}
public class Main{
public static void main(String[] args) {
Dog d = new Dog();
d.sound();
d.bark();
}
}
Types of Inheritance in Java
Java supports different types of inheritance to model relationships between classes.
Single Inheritance
One child class inherits from one parent class.
Multilevel Inheritance
A class inherits from another inherited class, forming a chain.
Hierarchical Inheritance
Multiple child classes inherit from the same parent class.
Multiple Inheritance
Java does not support multiple inheritance with classes. It is achieved using interfaces.
Hybrid Inheritance
Hybrid inheritance is not supported with classes but can be implemented using interfaces.
Advantages of Inheritance
- Promotes code reusability.
- Reduces duplicate code.
- Supports method overriding.
- Improves maintainability.
- Represents real-world relationships.
- Makes applications easier to extend.
Important Points About Inheritance
- A child class inherits all accessible fields and methods of its parent.
- Private members of the parent class are not directly accessible.
- Java supports only single inheritance with classes.
- The super keyword is used to access parent class members.
- The extends keyword is used to create inheritance.
Real-World Example of Inheritance
Consider a company management system where an Employee class contains common information like name and salary. Classes such as Manager, Developer, and Tester inherit from the Employee class. They reuse common properties while adding their own unique features.
Summary
Java inheritance is a powerful OOP feature that enables one class to inherit the properties and methods of another class. It promotes code reuse, improves maintainability, and creates logical relationships between classes. Java supports single, multilevel, and hierarchical inheritance using the extends keyword, while multiple inheritance is achieved through interfaces.