It is used when creating a class that is used only once on the spot.
Normally, you declare a class that implements an interface, create an instance of that class, and call a method, but with an anonymous class, you can declare the interface and use the method at the same time.
This time, I used a self-made interface with a method called output.
IPrint
public interface IPrint {
void output();
}
Create a class that implements the IPrint interface and describe the processing details in the method.
PrintImpl
public class PrintImpl implements IPrint{
@Override
public void output() {
System.out.println("aaa");
}
}
Call it in the execution class.
Main
public class Main {
public static void main(String[] args) {
IPrint ip = new PrintImpl();
ip.output();//On the console"aaa"Is output
}
}
You can use IPrint methods in the execution class without creating a class that implements the interface.
Main
public class Main {
public static void main(String[] args) {
IPrint ip = new IPrint() {
@Override
public void output() {
System.out.println("aaa");
}
};
ip.output();
}
}
In addition, you can reduce the number of lines with a lambda expression.
Main
public class Main {
public static void main(String[] args) {
IPrint ip = () -> System.out.println("xxxx");
ip.output(); // "xxxx"Is output
}
}
If you add a new method that is not in the interface, it will not be received as an interface type variable when the instance is created.
Main
public class Main3 {
public static void main(String[] args) {
new IPrint() {
@Override
public void output() {
System.out.println("aaa");
}
public void output2() {
System.out.println("bbb");
}
}.output2();
}
}
Recommended Posts