没有使用匿名内部类:
interface A {
public void printinfo();
}
class B implements A {
@Override
public void printinfo() {
System.out.println("Hello World!");
}
}
class C {
public void fun1() {
fun2(new B());
}
public void fun2(A a) {
a.printinfo();
}
}
public class niminglei {
public static void main(String[] args) {
C c = new C();
c.fun1();
}
}
接口的实现只使用一次,那么就没必要单独定义一个子类B,此时使用匿名内部类是这样:
interface A {
public void printinfo();
}
class C {
public void fun1() {
fun2(new A() {
@Override
public void printinfo() {
System.out.println("Hello World!");
}
});
}
private void fun2(A a) {
a.printinfo();
}
}
public class niminglei {
public static void main(String[] args) {
C c = new C();
c.fun1();
}
}
|
|