如果匿名类被定义为接口(interface)的类型,那么匿名类会实现该接口(interface),但是,如果它被定义为另一个类的类型(如下所示),它似乎不会扩展该类(正如我所言)被告知确实如此)。
public class AnonymousClassTest {
// nested class
private class NestedClass {
String string = "Hello from nested class.";
}
// entry point
public static void main (String args[]){
AnonymousClassTest act = new AnonymousClassTest();
act.performTest();
}
// performs the test
private void performTest(){
// anonymous class to test
NestedClass anonymousClass = new NestedClass() {
String string = "Hello from anonymous class.";
};
System.out.println(anonymousClass.string);
}
}
这里,如果匿名类扩展了嵌套类,那么输出将是“Hello from anonymous class。”,但是当运行时,输出将显示“Hello fromnested class。”
最佳答案
字段不可覆盖。如果一个类声明了一个名为 string
的字段,并且子类也声明了一个名为 string
的字段,则有两个名为 string
的独立字段。例如这个程序:
class Parent {
public String string = "parent";
public int getInt() {
return 1;
}
}
class Child extends Parent {
public String string = "child"; // does not override Parent.string
// overrides Parent.getInt():
public int getInt() {
return 2;
}
}
public class Main {
public static void main(final String... args) {
Child child = new Child();
System.out.println(child.string); // prints "child"
System.out.println(child.getInt()); // prints "2"
Parent childAsParent = child;
System.out.println(childAsParent.string); // prints "parent" (no override)
System.out.println(childAsParent.getInt()); // prints "2" (yes override)
}
}
打印
child
2
parent
2
因为 childAsParent
具有 Parent
类型,因此引用 Parent
中声明的字段,即使实际实例具有运行时类型 child
。
因此,如果您修改演示以使用方法而不是字段,您将看到您期望的结果。
关于java - 在 Java 中,匿名类与其定义的类型有什么关系?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21869294/