Java internal classes are divided into: member internal classes, static nested classes, method internal classes, and anonymous internal classes.
In the Java world, anonymous internal class syntax is provided to help everyone simplify their code. This article briefly describes its common patterns in the form of code from interfaces, abstract classes and regular classes.
1. Interface mode
public interface IWriter {void write();}public static void main(String[] args) {IWriter writer = new IWriter() {@Overridepublic void write() {System.out.println("IWriter write...");}};writer.write();} 2. Abstract Classes
public abstract class AbstractWriter {public abstract void write();}public static void main(String[] args) {AbstractWriter abstractWriter = new AbstractWriter() {@Overridepublic void write() {System.out.println("AbstractWriter write...");}};abstractWriter.write();}3. General Class
public class TextWriter implements IWriter {@Overridepublic void write() {System.out.print("text writer..");}}public static void main(String[] args) {TextWriter textWriter = new TextWriter() {@Overridepublic void write() {System.out.println("TextWriter 2 write...");}};textWriter.write();} 4. Use in the thread
public static void main(String[] args) {Thread thread = new Thread() {@Overridepublic void run() {new IWriter() {@Overridepublic void write() {System.out.println("IWriter thread write...");}}.write();}};thread.run();} 5. Conclusion
From the above, we can see that in fact, whether it is an interface, abstract class, or anonymous internal class derived from regular classes, the usage is the same. The reason why this is a syntactic sugar is that when the compiler compiles the anonymous internal class into different classes. This is actually the same as writing the implementation class separately and then calling it. For details, you can refer to the generated directory after compilation. As shown in the screenshot below: