Inheritance in Java allows a class to acquire properties and behaviors of another class. It helps in code reusability, maintainability, and enables method overriding.
Inheritance is a mechanism where one class (child/subclass) inherits the properties and methods of another class (parent/superclass). This relationship promotes code reuse and logical organization of classes.
The main objectives of using inheritance are to reduce code duplication, organize code efficiently, and enable runtime polymorphism, where a parent reference can point to a child object.
Inheritance reduces code redundancy, enhances maintainability, and supports method overriding. For example, a Dog class can inherit from Animal class, reusing its eat() method while adding new behavior bark().
Inheritance can lead to tight coupling between classes, making changes in the parent affect children. Improper use can increase complexity. Not all relationships fit an IS-A model, so inheritance may not always be appropriate.
Java supports several types of inheritance:
Single Inheritance: A child class inherits from one parent class.
Multilevel Inheritance: A chain of inheritance where a class inherits from a parent, which in turn inherits from its parent.
Hierarchical Inheritance: Multiple child classes inherit from a single parent class.
Multiple Inheritance through Interfaces: Java does not support multiple class inheritance directly, but a class can implement multiple interfaces.
// Parent class
class Animal {
void eat() {
System.out.println("Eating...");
}
}
// Child class
class Dog extends Animal {
void bark() {
System.out.println("Barking...");
}
}
// Main class
public class TestInheritance {
public static void main(String args[]) {
Dog d = new Dog();
d.eat(); // inherited method
d.bark(); // child method
}
}
In the example, the Dog class inherits from Animal. The Dog object can call both its own bark() method and the inherited eat() method, demonstrating reusability.
Use inheritance only when classes have a clear IS-A relationship. Prefer composition over inheritance when possible. Keep parent classes general and child classes specific to maintain flexibility and readability.