Default Methods for Logging in Interfaces in Java


Write a Java program to demonstrate the use of an interface with a default method for logging

  • The Logger interface defines a method log(String message) for logging messages and a default method logError(String errorMessage) for logging error messages. The logError method internally calls the log method to log the error message prefixed with "Error: ".
  • The ConsoleLogger class implements the Logger interface and provides an implementation for the log method by printing the message to the console.
  • In the Main class, an instance of ConsoleLogger is created and referenced by the Logger interface. This allows us to call both the log and logError methods through the interface reference. When logError is called, it internally invokes the log method with the error message.

Source Code

interface Logger
{
	void log(String message);
 
	default void logError(String errorMessage)
	{
		log("Error: " + errorMessage);
	}
}
 
class ConsoleLogger implements Logger
{
	@Override
	public void log(String message)
	{
		System.out.println("Log : " + message);
	}
}
 
public class Main
{
	public static void main(String[] args)
	{
		Logger logger = new ConsoleLogger();
		logger.log("Info message");
		logger.logError("Something went wrong");
	}
}

Output

Log : Info message
Log : Error: Something went wrong

Example Programs