1. 接口模式

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.抽象类

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.常规类

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.在线程中使用

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.结语

综上可以看出,其实不管是接口中,抽象类,还是常规类派生出来的匿名内部类,其用法都是一样的。之所以说这个是一个语法糖,其本质是编译器在编译的时候,将匿名内部类单独编译成不多个不同的class,这个和单独写实现类后再调用其实本质是一样,具体可以参见编译后生成目录.如下截图所示:

java中匿名内部类总结-LMLPHP

05-25 21:55