What is the default method?

Default Method

  • A default method in Java is a method defined in an interface that includes a default implementation.
  • This means that classes implementing the interface are not required to provide an implementation for the default method.
  • Default methods allow interfaces to evolve over time by adding new methods without breaking existing implementations.

❓ How is it used?

  • Default methods are declared with the default keyword inside an interface.
  • If a class implements the interface, it can either inherit the default method or override it with its own implementation.

Example:

public interface Vehicle {
    void accelerate();

// Default method with a body
default void start() {
System.out.println("Starting the vehicle");
}


}  

In this example:

- The Vehicle interface has a default method start(), which provides a basic implementation for starting a vehicle.

- Any class implementing Vehicle will inherit the start() method unless it chooses to override it.

Example of Implementation:

public class Car implements Vehicle {
    @Override
    public void accelerate() {
        System.out.println("Car is accelerating");
    }

// Inherits the default start() method from Vehicle


}  

In this case:

- The Car class implements the Vehicle interface and provides its own implementation for the accelerate() method.

- Since Car does not override start(), it will use the default implementation from the Vehicle interface.

Key Features:

  1. Backward Compatibility:
  2. Default methods allow adding new methods to interfaces without forcing all implementing classes to update.
  3. Example: Adding start() to Vehicle without breaking existing classes that implement the interface.
  4. Optional Override:
  5. Implementing classes can override a default method if they need a custom implementation. Otherwise, they inherit the default version.
  6. Multiple Inheritance:
  7. If a class implements multiple interfaces with default methods having the same signature, it must explicitly override the method to resolve the conflict.
  8. Example:

java public class Truck implements Vehicle, Machine { @Override public void start() { // Custom implementation to resolve conflict between Vehicle and Machine } }


Summary:

A default method in Java is a method in an interface that provides a default implementation, allowing classes to inherit it without needing to override it. This feature helps with backward compatibility and allows interfaces to evolve without breaking existing code.