Category : Java | Sub Category : Java8 Features | By Prasad Bonam Last updated: 2023-11-13 04:51:25 Viewed : 235
Default methods in Java were introduced as part of Java 8 to provide a way to add new methods to interfaces without breaking existing implementations. Before Java 8, interfaces could only declare abstract methods, and any change to an interface would require modifying all classes that implemented that interface. Default methods address this issue and offer several benefits:
Backward Compatibility:
API Evolution:
Library Enhancements:
Reduced Boilerplate Code:
Interface Extension:
Enhanced Collections API:
Collection
interface and its subinterfaces in the Java Collections Framework (e.g., List
, Set
, Map
) allows for more expressive and concise code when working with collections.javapublic interface Shape {
double area();
// Default method providing a default implementation
default void printArea() {
System.out.println("Area: " + area());
}
}
public class Circle implements Shape {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
@Override
public double area() {
return Math.PI * radius * radius;
}
}
public class Rectangle implements Shape {
private double width;
private double height;
public Rectangle(double width, double height) {
this.width = width;
this.height = height;
}
@Override
public double area() {
return width * height;
}
}
In this example, the Shape
interface has a default method printArea()
. Implementing classes such as Circle
and Rectangle
can choose to use this default method or provide their own implementation. This allows for a common method to be introduced to an existing interface without breaking the implementations.