Default Methods in Java 8 - Shaikh
Default Methods in Java 8 - Shaikh
Default methods, also known as defender methods or virtual extension methods, were
introduced in Java 8 to provide a way to add new methods to interfaces without breaking
compatibility with classes that implement those interfaces. This feature was added to address
the challenge of evolving existing interfaces without forcing developers to modify all
implementing classes.
1. **Introduction of New Methods:** Default methods allow developers to add new methods to
existing interfaces without requiring changes in the classes that implement those interfaces.
3. **Use Case:** Default methods are particularly useful when you want to add new methods to
an interface in order to introduce new functionality or behavior in a backward-compatible way.
**Example:**
```java
interface Shape {
double area();
void draw();
}
```
```java
interface Shape {
double area();
void draw();
```java
class Circle implements Shape {
private double radius;
@Override
public double area() {
return Math.PI * radius * radius;
}
@Override
public void draw() {
System.out.println("Drawing a circle.");
}
}
**Notes:**
- Default methods provide a way to extend existing interfaces without breaking the code that
uses those interfaces.
- In case of conflicts (when a class implements multiple interfaces with default methods of the
same name), the implementing class must provide its own implementation to resolve the
conflict.
- Default methods cannot access private fields or methods of implementing classes.
- Interfaces can also have static methods with implementations in Java 8.
Default methods significantly enhanced the flexibility of Java interfaces by allowing them to
evolve over time while maintaining backward compatibility. This feature is particularly valuable in
library and framework design where interfaces are widely used by various implementations.