Explain Inheritance in Java

Inheritance in Java is a fundamental feature of object-oriented programming that allows one class to inherit the properties and behaviors (methods) of another class. This mechanism helps in code reusability and establishing a relationship between classes. In Java, a class that is inherited from another class is called a subclass (or child class), while the class from which it inherits is known as the superclass (or parent class).

Using inheritance, you can create a new class based on an existing class, augmenting or overriding its behaviors while still incorporating all the existing functionality. This creates a hierarchical relationship between the classes.

Here is an example of inheritance in Java:

class Animal { void sound() { System.out.println("Animal makes a sound"); } } class Dog extends Animal { void sound() { System.out.println("Dog barks"); } } public class TestInheritance { public static void main(String[] args) { Animal myDog = new Dog(); myDog.sound(); // Outputs: Dog barks } }

Inheritance Java Inheritance Object-Oriented Programming Java Classes Java Code Reusability Subclass Superclass