A default method in Java is declared in an interface and has a default implementation. It provides a default implementation for an interface function, which can be overridden in an interface-implementing class.
Here is an example of a default method in Java:
public interface Vehicle {
void start();
void stop();
default void honk() {
System.out.println("Beep beep!");
}
}
public class Car implements Vehicle {
public void start() {
System.out.println("Starting the car");
}
public void stop() {
System.out.println("Stopping the car");
}
public static void main(String[] args) {
Car car = new Car();
car.start();
car.honk();
car.stop();
}
}
Output:
Starting the car
Beep beep!
Stopping the car
- The Vehicle interface has a default function honk() in this example, which gives a default implementation for the honk() method.
- The Car class implements the Vehicle interface and overrides the start(), stop(), and honk() methods, but not the honk() function.
- As a result, the honk() method in the Car class employs the Vehicle interface's default implementation.
- When an instance of the Car class executes its methods, the honk(), we can see that unction utilizes the default implementation and prints "Beep beep!" to the console.
- Log in to post comments