Inheritance and Polymorphism Assignment
Inheritance and Polymorphism Assignment
from an existing class. This new class is referred to as the "child" or "subclass," while the original
and making code maintenance easier, as changes in the superclass are automatically reflected
in the subclass.
Example:
```java
class Parent {
void display() {
System.out.println("Parent class");
void show() {
System.out.println("Child class");
}
```
2. Multilevel Inheritance: A class inherits from a child class, forming a chain of inheritance.
Example:
```java
class Grandparent { }
```
Example:
```java
class Parent { }
```
4. Multiple Inheritance (via Interfaces in Java): A class can inherit from multiple interfaces.
Example:
```java
interface Interface1 { }
interface Interface2 { }
```
Multiple inheritance through classes is not supported in Java to avoid the ambiguity caused by
the "Diamond Problem." The Diamond Problem occurs when a
class inherits from two classes that have a common base class, resulting in conflicts due to
resolves this by allowing multiple inheritance only through interfaces, providing flexibility without
Method overriding occurs when a subclass provides a specific implementation of a method that is
polymorphism, allowing the program to call the overridden method of the subclass.
Example:
```java
class Animal {
void sound() {
System.out.println("Animal sound");
@Override
void sound() {
System.out.println("Bark");
```
Here, `sound()` method is overridden in `Dog` class, allowing it to have its own implementation.
1. Compile-time Polymorphism:
- Achieved by having multiple methods with the same name but different parameters.
2. Runtime Polymorphism: