没有名字
内部的类
只使用一次
前提条件:必须继承一个父类,或者implements 一个 接口 interface
abstract class Person {
public abstract void eat();
}
class Child extends Person {
public void eat() {
System.out.println("eat something");
}
}
public class Demo {
public static void main(String[] args) {
Person p = new Child();
p.eat();
}
}
如果Child类使用一次,将变得多余,可以改为如下代码
abstract class Person {
public abstract void eat();
}
public class Demo {
public static void main(String[] args) {
new Person(){
public void eat() {
sout("eat !!!");
}
}.eat();
}
}
interface Person {
public void eat();
}
public class Demo {
public static void main(String[] args) {
new Person(){
public void eat() {
sout("eat !!!");
}
}.eat();
}
}
此处 new Person( )看似实例化了一个接口,事实并非如此,接口式的匿名内部类是实现了一个接口的匿名类。而且只能实现一个接口。
new Thread() {
public void run() {
for (int i = 1; i <= 5; i++) {
System.out.print(i + " ");
}
}
}.start();
new Thread(new Runnable() {
联系客服