**Inheritance** is a key feature of Object-Oriented Programming (OOP) that allows a class to inherit properties and methods from another class, thereby enabling code reuse and extending the functionality of existing classes. 1. **How Inheritance Works**: - The child class (subclass) inherits all public and protected members (variables and methods) from the parent class (superclass). - The subclass can then **override** the methods of the parent class to provide its own specific implementation, or **extend** the functionality by adding new methods. - Inheritance is a "is-a" relationship. For example, a `Dog` class **is a** type of `Animal`, so it can inherit properties from the `Animal` class. 2. **Example**:
\begin{verbatim}
// Parent class (Superclass)
class Animal { String name; public void eat() { System.out.println("This animal is eating."); } public void sleep() { System.out.println("This animal is sleeping."); }
} // Child class (Subclass) inheriting from Animal
class Dog extends Animal { public void bark() { System.out.println("The dog is barking."); } // Overriding the eat method @Override public void eat() { System.out.println("The dog is eating dog food."); }
} public class Test { public static void main(String[] args) { Dog dog = new Dog(); dog.name = "Buddy"; dog.eat(); // Output: The dog is eating dog food. dog.sleep(); // Output: This animal is sleeping. dog.bark(); // Output: The dog is barking. }
}
\end{verbatim}
- In this example: - The `Dog` class inherits the `eat()` and `sleep()` methods from the `Animal` class. - The `Dog` class also has a unique method `bark()`. - The `Dog` class **overrides** the `eat()` method to provide specific behavior. 3. **Benefits of Inheritance**: - **Code Reusability**: By inheriting from a parent class, the child class does not need to write the same code again. - **Modularity**: Inheritance allows for better organization of code by creating hierarchies, making it easier to maintain and extend the codebase.