Default Methods in Interfaces in Java


Create a Java program to demonstrate a class implementing an interface with default methods

  • Greet is an interface with two methods: sayHello() and a default method sayGoodbye().
  • The sayGoodbye() method in the Greet interface has a default implementation, which prints "Goodbye!" to the console.
  • Person is a class that implements the Greet interface. It provides an implementation for the sayHello() method.
  • In the Main class, an instance of Person is created. The sayHello() method is called on this instance, which prints "Hello, there!" to the console. Then, the sayGoodbye() method is called, which invokes the default implementation from the interface, printing "Goodbye!" to the console.

Source Code

interface Greet
{
    void sayHello();
 
    default void sayGoodbye()
	{
        System.out.println("Goodbye!");
    }
}
 
class Person implements Greet
{
    @Override
    public void sayHello()
	{
        System.out.println("Hello, there!");
    }
}
 
public class Main
{
    public static void main(String[] args)
	{
        Person person = new Person();
        person.sayHello();
        person.sayGoodbye();
    }
}

Output

Hello, there!
Goodbye!

Example Programs