Abstract methods vs. default methods in interfaces in Java

Interfaces in Java provide a way to define contracts that classes can implement. They typically contain abstract methods, which are by default public and must be implemented by the classes that implement the interface. However, starting from Java 8, interfaces can also contain default methods. Let’s explore the differences between abstract methods and default methods in interfaces.

Abstract Methods

Abstract methods in interfaces are declarations without an implementation. They are typically used to define a set of operation signatures that implementing classes must provide. Here’s an example of an interface with an abstract method:

public interface Drawable {
    void draw();
}

In the above code, draw() is an abstract method in the Drawable interface. Any class that implements this interface must provide an implementation for the draw() method.

Default Methods

Default methods were introduced in Java 8 and provide a way to add methods with a default implementation in interfaces. These methods have an actual implementation in the interface itself, which can be used by all implementing classes. Here’s an example:

public interface Drawable {
    void draw();
    
    default void resize() {
        System.out.println("Resizing the drawable object.");
    }
}

In the code snippet above, resize() is a default method added to the Drawable interface. Unlike abstract methods, classes that implement this interface are not required to provide an implementation for default methods. Implementing classes can choose to override the default method if needed.

Key Differences

Role and Usage

Inheritance

Multiple Inheritance

Conclusion

Abstract methods and default methods in interfaces serve different purposes. Abstract methods define a contract that must be fulfilled by implementing classes, while default methods provide a default implementation that can be used by all implementing classes. Understanding their differences is crucial when designing and implementing interfaces in Java.

#Java #InterfaceMethods