Anonymous classes¶
Basics¶
Anonymous classes work the same as local classes. The only difference is that anonymous classes:
- have no name
- should be declared if we only need them once
Anonymous class syntax¶
Creating an anonymous class object is almost identical to creating a regular object. The difference is that when creating an object, all the required methods are implemented. The expression consists of:
- the
new
operator or the use of lambda in the case of [interface] (md-interface) for a function - the name of the interface we implement or the abstract class we inherit
- constructor parameters (in the case of an interface we use an empty constructor)
- class/interface body
Within the anonymous class, we can declare:
- fields (including static fields)
- methods (including static methods)
- constants
However, you cannot declare:
- constructors
- interfaces
- static initialization blocks
The following example shows how to implement an anonymous class using the new
keyword and then using a lambda:
public interface ClickListener {
void onClick();
}
public class UIComponents {
void showComponents() {
// an anonymous class implementation using the new keyword
ClickListener buttonClick = new ClickListener() {
@Override
public void onClick() {
System.out.println("On Button click!");
}
};
// end of anonymous class implementation
buttonClick.onClick();
// an anonymous class implementation using lambda
// this is possible because ClickListener is a functional interface, ie it has one method to implement
ClickListener checkboxClick = () -> System.out.println("On Checkbox click!");
checkboxClick.onClick();
}
}
The next example shows the additional capabilities of an anonymous class implemented using the new
keyword:
public interface ClickListener {
void onClick();
}
void showComponentsV2() {
// anonymous class implementation
ClickListener buttonClick = new ClickListener() {
private String name; // field in anonymous class
private static final String BUTTON_CLICK_MESSAGE ="On Button click!"; // static field in anonymous class
public void sayHello() { // method implementation in anonymous class
System.out.println("I am new method in anonymous class");
}
@Override
public void onClick() {
sayHello();
System.out.println(BUTTON_CLICK_MESSAGE);
}
};
}
Access to parent classes¶
Anonymous classes can reference parent class fields and local variables as long as they are final. As with nested classes, variables with the same names as the parent class fields override their properties.