Skip to content

Java Default method

Imagine you have a bunch of classes that implement the same interface. Traditionally, if you wanted to add a new method to that interface, you'd have to go and update every single class to provide an implementation for that method.

But fear not, because Java Default Methods to save the day! These little methods allow you to add new functionality to interfaces without breaking existing implementations. How cool is that?

Here's the deal: when you add a default method to an interface, you're basically providing a default implementation for that method right there in the interface itself. And here's the magic – any class that implements that interface automatically gets access to that default implementation. No need to rush around updating all your classes!

But hold on, there's more! Default methods aren't just about saving you from endless code updates. They also give you the flexibility to add new features to your interfaces without worrying about breaking compatibility with older code. It's like giving your interfaces a shiny new upgrade without causing confusion in your existing codebase.

java
interface Greeting {
    default void sayHello() {
        System.out.println("Hello, friend!");
    }
}

class Person implements Greeting {
    // No need to implement sayHello() in Person class!
}

public class DefaultMethodExample {
    public static void main(String[] args) {
        Person person = new Person();
        person.sayHello(); // Output: Hello, friend!
    }
}

Isn't that marvelous? In our example, we have an interface called Greeting with a Default Method sayHello(). Now, here's where the magic happens—when the Person class implements the Greeting interface, it automatically inherits the default implementation of sayHello(), without needing to provide its own implementation. It's like inheriting a superpower without any extra effort!

java
interface Greeting {
    default void sayHello() {
        System.out.println("Hello, friend!");
    }

    default void sayGoodbye() {
        System.out.println("Goodbye, friend!");
    }
}

class Person implements Greeting {
    // No need to implement sayHello() or sayGoodbye() in Person class!
}

public class DefaultMethodEvolution {
    public static void main(String[] args) {
        Person person = new Person();
        person.sayHello();    // Output: Hello, friend!
        person.sayGoodbye();  // Output: Goodbye, friend!
    }
}

See how we added a new Default Method sayGoodbye() to our Greeting interface? And yet, the Person class still works perfectly fine without needing to change a single line of code.

Waytojava is designed to make learning easier. We simplify examples for better understanding. We regularly check tutorials, references, and examples to correct errors, but it's important to remember that humans can make mistakes.