Private Methods for Validation in Interfaces in Java


Create a Java program to demonstrate the use of an interface with private methods for validation

  • ValidationDemo class implements the Validator interface.
  • The Validator interface declares a default method isValid(String input) for validating the input string.
  • The isValid() method calls two private methods for validation: validateLength() and validateContent().
  • Both validateLength() and validateContent() methods are private and only accessible within the interface. They are used internally for validation.
  • In the main() method of ValidationDemo, an instance of ValidationDemo is created.
  • It takes input from the user and checks its validity using the isValid() method of the Validator interface.
  • If the input is valid based on the defined validation rules, it prints "Input is Valid"; otherwise, it prints "Input is Not Valid".

Source Code

import java.util.Scanner;
 
public class ValidationDemo implements Validator
{
	public static void main(String[] args)
	{
		ValidationDemo validator = new ValidationDemo();
		Scanner scanner = new Scanner(System.in);
 
		System.out.println("Enter a String to Validate : ");
		String input = scanner.nextLine();
 
		if (validator.isValid(input))
		{
			System.out.println("Input is Valid");
		}
		else
		{
			System.out.println("Input is Not Valid");
		}
 
		scanner.close();
	}
}
 
interface Validator// Define an interface with private methods for validation
{
	default boolean isValid(String input)
	{
		return validateLength(input) && validateContent(input);
	}
 
	private boolean validateLength(String input)
	{
		return input.length() >= 5;
	}
 
	private boolean validateContent(String input)
	{
		return input.matches(".*[a-zA-Z]+.*");
	}
}

Output

Enter a String to Validate :
Joes1234
Input is Valid

Example Programs