代码:-
10. interface Foo { int bar(); }
11. public class Sprite {
12. public int fubar( Foo foo) { return foo.bar(); }
13. public void testFoo() {
14. fubar(
15. new Foo() { public int bar(){ return 1; } }
16. );
17. }
18. }
-我无法理解第 14 行到第 16 行。因为我从来没有在一种方法中看到过这样的东西。任何人都可以解释 14-16 没有行吗?
最佳答案
这称为 anonymous inner class .在您执行 new Foo() { ... }
时,将创建一个具有编译器生成名称的新类。这个新类实现了 Foo
接口(interface)。它大致相当于:
interface Foo { int bar(); }
public class Sprite {
public int fubar( Foo foo) { return foo.bar(); }
public class MyFoo implements Foo {
public int bar() { return 1; }
}
public void testFoo() {
fubar(
new MyFoo()
);
}
}
(我假设您的示例中 new
和 Foo
之间缺少空格是一个错误。)
关于java接口(interface)问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5906814/