In Java, inheritance is a key feature of object-oriented programming that allows a class (subclass or child class) to inherit properties and behaviours (methods and fields) from another class (superclass or parent class).
This enables code reuse, promotes modularity, and supports the concept of hierarchical classification.
Here are some key points about inheritance in Java:
A superclass is a class that is being inherited from.
A subclass is a class that inherits from another class (superclass).
Inheritance is represented by the extends keyword in Java.
class Animal { // Superclass void sound() { System.out.println("Animal makes a sound"); } } class Dog extends Animal { // Subclass void wagTail() { System.out.println("Dog wags its tail"); } }
class Animal { void sound() { System.out.println("Animal makes a sound"); } } class Dog extends Animal { @Override void sound() { System.out.println("Dog barks"); } }
Subclasses can provide a specific implementation for a method defined in the superclass. This is known as method overriding.
To override a method, the subclass must define a method with the same signature (name and parameters) as the superclass method.
The "@Override" annotation is used to indicate that a method is intended to override a superclass method.
class Animal { void sound() { System.out.println("Animal makes a sound"); } void sound(String animalName) { System.out.println("Animal makes a sound: " + animalName); } } class Dog extends Animal { @Override void sound() { System.out.println("Dog barks"); } void sound(String breed) { System.out.println("Dog barks: " + breed); } } public class Main { public static void main(String[] args) { // Creating instance of Dog Dog dog = new Dog(); dog.sound(); dog.sound("pitbull"); } }
Overloading occurs when a class has multiple methods with the same name but different parameter lists.
Overloaded methods in the superclass are not overridden in the subclass. Both methods can coexist.
Constructors are not inherited, but they are called implicitly or explicitly from the subclass constructor using the "super()" keyword.
If the superclass has multiple constructors, the subclass constructor must explicitly call one of them using "super()".
Inheritance is a powerful mechanism in Java that facilitates code reuse and promotes a hierarchical structure among classes.
However, it's essential to use inheritance judiciously to avoid tight coupling and maintain a clear and maintainable class hierarchy.