你有这个:
public class TestObject {
public String Hooray() {
return "Hooray!";
}
}
TestObject a = new TestObject() {
public String Boo() {
return "Booooo";
}
}
System.out.println(a.Boo());
你不能这样做。您可以在匿名内部类中创建新方法,事实上,您可以。但是您将无法a.Boo()
从外部调用,因为a
is aTestObject
并且TestObject
没有方法 named Boo
。这与您不能这样做的原因相同:
public class Base {
public void something ();
}
public class Derived extends Base {
public void another ();
}
Base b = new Derived();
b.another(); // b is a Base, it must be cast to a Derived to call another().
在上面你必须转换b
为 aDerived
来调用添加到派生类的新方法:
((Derived)b).another();
您不能使用匿名内部类(它们只是派生新子类的语法快捷方式)执行此操作的原因正是因为它们是匿名的 - 没有可供您将它们转换为的类型。
顺便说一句,您无法another()
通过 type访问的原因Base
很简单,当您考虑它时。虽然Derived
是 a Base
,但编译器无法知道它Base b
持有 aDerived
而不是其他Base
一些没有方法的子类another()
。
希望有帮助。