Inheritance in Java allows classes to inherit properties and methods from other classes, promoting code reusability and establishing a hierarchical relationship between classes. This principle of Object-Oriented Programming (OOP) lets a subclass utilize fields and methods of its superclass, except for constructors, which are not inherited.
Understanding Inheritance
- Superclass (Parent Class): The class whose features are being inherited.
- Subclass (Child Class): The class that inherits features from the superclass.
extends
Keyword: Used by a subclass to inherit from a superclass.
Advantages of Inheritance
- Code Reusability: Facilitates the reuse of existing code.
- Method Overriding: Allows a subclass to override a method from the superclass to provide a specific implementation.
- Polymorphism: Makes it possible to treat objects of a subclass as objects of a superclass.
Example 1: Basic Inheritance
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
// Superclass class Vehicle { void run() { System.out.println("Vehicle is running"); } } // Subclass class Car extends Vehicle { @Override void run() { System.out.println("Car is running safely"); } } public class TestInheritance { public static void main(String[] args) { Car myCar = new Car(); myCar.run(); // Outputs: Car is running safely } } |
Example 2: Multi-Level Inheritance
In multi-level inheritance, a subclass acts as a superclass for another subclass. This creates a “grandparent-parent-child” relationship between classes.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
// Superclass class Animal { void eat() { System.out.println("Eating..."); } } // Subclass of Animal class Bird extends Animal { void fly() { System.out.println("Flying..."); } } // Subclass of Bird class Sparrow extends Bird { void sing() { System.out.println("Singing..."); } } public class InheritanceTest { public static void main(String[] args) { Sparrow mySparrow = new Sparrow(); mySparrow.eat(); // From Animal class mySparrow.fly(); // From Bird class mySparrow.sing(); // From Sparrow class } } |
Key Points:
- Method Overriding: Both examples demonstrate overriding the superclass method in the subclass to provide a specialized implementation.
- Multi-Level Inheritance: The second example shows how inheritance can be extended across multiple levels, allowing a subclass to inherit methods from its superclass, which in turn inherits from its own superclass.
Conclusion
Inheritance is a cornerstone of OOP in Java, offering a systematic way to organize code, enhance reusability, and implement polymorphism. By allowing subclasses to inherit and override superclass methods, Java developers can create more maintainable and scalable applications. Understanding inheritance patterns and their applications is vital for effective Java programming.