Anonymous internal class summary in java and java Anonymous class Summary
In the world of java, the anonymous internal class syntax sugar is provided to help you simplify the Code. This article briefly describes the common modes of interfaces, abstract classes, and common classes in the form of code.
1. Interface Mode
public interface IWriter { void write();}public static void main(String[] args) { IWriter writer = new IWriter() { @Override public void write() { System.out.println("IWriter write..."); } }; writer.write();}
2. abstract class
public abstract class AbstractWriter { public abstract void write();} public static void main(String[] args) { AbstractWriter abstractWriter = new AbstractWriter() { @Override public void write() { System.out.println("AbstractWriter write..."); } }; abstractWriter.write();}
3. Regular Class
public class TextWriter implements IWriter { @Override public void write() { System.out.print("text writer.."); }}public static void main(String[] args) { TextWriter textWriter = new TextWriter() { @Override public 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() { @Override public void run() { new IWriter() { @Override public void write() { System.out.println("IWriter thread write..."); } }.write(); } }; thread.run();}
5. Conclusion
In summary, it can be seen that the usage of anonymous internal classes derived from the abstract classes and general classes is the same in the interface. This is a syntactic sugar. In essence, the compiler compiles anonymous internal classes into several different classes during compilation, this is essentially the same as writing an implementation class and then calling it. For details, see compile and generate a directory. as follows: