Govur University Logo
--> --> --> -->
...

Discuss the concept of inheritance in Java and provide an example of a subclass inheriting from a superclass.



In Java, inheritance is a fundamental concept of object-oriented programming that allows a class to inherit properties and behaviors from another class. The class that is being inherited from is called the superclass or parent class, and the class that inherits from it is called the subclass or child class. Here's an in-depth explanation of inheritance in Java along with an example:

Concept of Inheritance:
Inheritance enables the creation of a hierarchical relationship between classes, where subclasses inherit the characteristics of their superclass. This promotes code reuse, modularity, and the concept of "is-a" relationship. The subclass inherits the members (fields and methods) defined in the superclass, allowing it to extend or specialize the superclass's behavior while adding its own unique features.

Example of Subclass Inheriting from Superclass:

```
java`// Superclass
class Animal {
String name;

void eat() {
System.out.println("The animal is eating.");
}
}

// Subclass inheriting from Animal
class Dog extends Animal {
void bark() {
System.out.println("The dog is barking.");
}
}

// Subclass inheriting from Animal
class Cat extends Animal {
void meow() {
System.out.println("The cat is meowing.");
}
}`
```
In this example, we have a superclass `Animal` that has a field `name` and a method `eat()`. The `Dog` and `Cat` classes are subclasses of `Animal` and inherit its members. They also have their own specific methods `bark()` and `meow()`, respectively.

By inheriting from the `Animal` class, the `Dog` and `Cat` classes gain access to the `name` field and `eat()` method. Additionally, they can add their own unique behaviors. For instance, an instance of the `Dog` class can call the `eat()` method inherited from the `Animal` class, as well as the `bark()` method defined in the `Dog` class itself.

```
java`public class Main {
public static void main(String[] args) {
Dog dog = new Dog();
dog.name = "Buddy";
dog.eat(); // Output: The animal is eating.
dog.bark(); // Output: The dog is barking.

Cat cat = new Cat();
cat.name = "Whiskers";
cat.eat(); // Output: The animal is eating.
cat.meow(); // Output: The cat is meowing.
}
}`
```
In the `Main` class, we create instances of the `Dog` and `Cat` classes. We can access the `name` field and the `eat()` method inherited from the `Animal` class, as well as the specific methods `bark()` and `meow()` defined in the respective subclasses.

In summary, inheritance in Java allows subclasses to inherit properties and behaviors from a superclass, enabling code reuse, promoting modularity, and facilitating the creation of hierarchical relationships. Subclasses can extend the functionality of the superclass by adding their own unique features, resulting in a more flexible and modular code structure.