Interfaces for Custom Authentication in Java


Create a Java program to demonstrate the use of an interface for custom authentication

  • The Authenticator interface declares a single method authenticate(String username, String password) that returns a boolean indicating whether the authentication is successful or not.
  • In the main method of the Main class, an instance of the Authenticator interface is created using a lambda expression. Inside the lambda expression, authentication logic is simulated by checking if the provided username and password match a predefined value.
  • The username and password are defined.
  • The authenticate method of the Authenticator interface is called with the provided username and password.
  • The result of the authentication is printed to the console.

Source Code

interface Authenticator
{
	boolean authenticate(String username, String password);
}
 
public class Main
{
	public static void main(String[] args)
	{
		Authenticator authenticator = (username, password) -> {
			// Simulate authentication logic
			return username.equals("Admin") && password.equals("Admin123");
		};
 
		String username = "Admin";
		String password = "Admin123";
 
		boolean isAuthenticated = authenticator.authenticate(username, password);
		System.out.println("Is User Authenticated? " + isAuthenticated);
	}
}

Output

Is User Authenticated? true

Example Programs