In the Java world, an anonymous inner class syntax sugar is provided to help you simplify your code, and this article briefly describes its common patterns in code from interfaces, abstract classes, and general classes.
1. Interface mode
Public Interface iwriter { void write ();} Public Static void Main (string[] args) { new iwriter () { @Override public void write () { System.out.println ("Iwriter write ...");} ; Writer.write ();}
2. Abstract class
Public Abstract classAbstractwriter { Public Abstract voidwrite ();} Public Static voidMain (string[] args) {abstractwriter abstractwriter=NewAbstractwriter () {@Override Public voidwrite () {System.out.println ("Abstractwriter Write ..."); } }; Abstractwriter.write ();}
3. General Class
Public classTextWriterImplementsIwriter {@Override Public voidwrite () {System.out.print ("Text writer ..."); }} Public Static voidMain (string[] args) {TextWriter TextWriter=NewTextWriter () {@Override Public voidwrite () {System.out.println ("TextWriter 2 Write ..."); } }; Textwriter.write ();}
4. Using in the thread
Public Static void Main (string[] args) { new Thread () { @Override publicvoid Run () { new iwriter () { @Override public void Write () { System.out.println ("Iwriter thread write ...");} . Write (); } }; Thread.run ();}
5. Conclusion
As can be seen, in fact, regardless of the interface, abstract class, or general class derived from the anonymous inner class, its usage is the same. The reason is that this is a syntactic sugar, the essence of the compiler at the time of compilation, the anonymous internal class is compiled separately into a different class, this and a separate write implementation class and then call the actual nature is the same, specifically, you can see the compilation of the directory. As shown below:
Anonymous inner class summary in Java