The Java inner class is divided into member inner class, Static nested class, Method inner class, anonymous inner class.
In the Java world, an anonymous inner class syntax is provided to help simplify 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} {
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. General 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 writ E () {
System.out.println ("TextWriter 2 write ...");
}
;
Textwriter.write ();
4. Use in Threads
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
As you can see, in fact, whether it is an interface, an abstract class, or a general class derived from the anonymous inner class, its use is the same. The reason is that this is a grammatical sugar, the essence of the compiler at compile time, the anonymous internal class to be compiled into not many different classes, this and the individual to write the implementation of the class after the call is actually the same, you can see the compilation of the build directory. The screenshot below shows: