只使用一次方法时,用匿名类更方便
package anonymousclass1;
public interface A {
String hello();
}
package anonymousclass1;
public class B implements A{
@Override
public String hello() {
return "Hello World";
}
}
package anonymousclass1;
public class C {
public void test(A a) {
System.out.println(a.hello());
}
public static void main(String[] args) {
new C().test(new B());
new C().test(new A() {
/**
* 匿名内部类,只使用一次
*/
@Override
public String hello() {
// TODO Auto-generated method stub
return "hello world 2";
}
});
}
}
//执行结果
Hello World
hello world 2