Mark As Completed Discussion

Default Methods

In Java 8, default methods were introduced in interfaces to provide a way to add new functionality to existing interfaces without breaking compatibility with the classes that implemented those interfaces.

Default methods in interfaces have a method body, allowing them to provide a default implementation of the method. Classes that implement the interface can use this default implementation or override it with their own implementation.

Let's take a look at an example:

TEXT/X-JAVA
1interface Animal {
2
3    void eat();
4
5    default void sleep() {
6        System.out.println("Animal is sleeping");
7    }
8
9}
10
11class Dog implements Animal {
12
13    public void eat() {
14        System.out.println("Dog is eating");
15    }
16
17}
18
19public class Main {
20
21    public static void main(String[] args) {
22        Dog dog = new Dog();
23        dog.eat();
24        dog.sleep();
25    }
26
27}

In this example, we have an interface Animal with a default method sleep(). The class Dog implements the Animal interface and provides its own implementation of the eat() method. The sleep() method inherits the default implementation from the interface.

The output of the above program will be:

SNIPPET
1Dog is eating
2Animal is sleeping
3```\n\n\nDefault methods in interfaces are useful when we want to add new functionality to interfaces in a backward-compatible manner. They provide a way to extend interfaces without breaking existing code that implements those interfaces.
JAVA
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment