package essentials;

/*
 * Examples showing how to declare and instantiate an anonymous class. An
 * anonymous class declaration is an expression that defines the members of a
 * class and creates an instance of that class at the same time. They are
 * relevant for code that only needs to use a class once. Some anonymous class
 * declarations can also be written more succinctly as lambda expressions.
 */
public class AnonymousClasses
{
	private static final int MIN_LENGTH = 5;
	
private static final StringSelector SELECT_ALL = new StringSelector()
{ @Override public boolean accept(String string) { return true; } };
public static void main(String[] args) { // Simple anonymous class implementing an interface StringSelector selectUpperCase = new StringSelector() { @Override public boolean accept(String string) { return string.equals(string.toUpperCase()); } }; System.out.println(selectUpperCase.getClass());
System.out.println(selectUpperCase.accept("UPPER"));
// Anonymous class with variable capture int maxLength = 5; StringSelector selectSizeAndNotEquals = new StringSelector() { @Override public boolean accept(String string) { return !string.equals(args[0]) && string.length() <= maxLength && string.length() >= MIN_LENGTH; } }; if (args.length > 0 && args[0] != null ) { System.out.println(selectSizeAndNotEquals.accept("A string")); } // Anonymous class through inheritance and with field and methods Object object = new Object() {
private int numberOfCalls = 0; private String getMessage() { return String.format("%s (called %d times)", super.toString(), ++numberOfCalls);
} @Override public String toString() {
return getMessage();
} }; System.out.println(object.toString()); System.out.println(object.toString()); } } interface StringSelector { boolean accept(String string); }