You are on page 1of 3

**Default Methods in Java 8**

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.

**Key Points about Default Methods:**

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.

2. **Default Method Implementation:** Default methods provide a default implementation within


the interface itself. This default implementation is inherited by classes that implement the
interface unless the implementing class overrides the default method.

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:**

Suppose we have an existing interface `Shape`:

```java
interface Shape {
double area();
void draw();
}
```

We want to introduce a new method `defaultDescription` to provide a default description for


shapes:

```java
interface Shape {
double area();
void draw();

default String defaultDescription() {


return "This is a shape.";
}
}
```
Now, classes that implement the `Shape` interface will inherit the `defaultDescription` method:

```java
class Circle implements Shape {
private double radius;

public Circle(double radius) {


this.radius = radius;
}

@Override
public double area() {
return Math.PI * radius * radius;
}

@Override
public void draw() {
System.out.println("Drawing a circle.");
}
}

public class DefaultMethodExample {


public static void main(String[] args) {
Circle circle = new Circle(5.0);
System.out.println("Area: " + circle.area());
System.out.println("Description: " + circle.defaultDescription());
}
}
```

**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.

You might also like