【问题标题】:In Java what is the relationship of an anonymous class to the type it is defined as?在 Java 中,匿名类与其定义的类型有什么关系?
【发布时间】:2014-02-19 01:42:48
【问题描述】:

如果匿名类被定义为接口的类型,那么匿名类实现了接口,但是如果它被定义为另一个类的类型(如下所示),它似乎并没有扩展类(因为我被告知确实如此)。

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。”,但是当运行时,输出显示为“来自嵌套类的 Hello。”

【问题讨论】:

  • 我认为您在匿名类中声明了第二个字段。尝试删除字符串修饰符。使它成为 string="来自匿名类的你好。"并使字符串字段非私有。
  • 这是真的,但是我试图覆盖匿名类中的字符串。要访问父字符串,我不应该使用super.string吗?
  • 啊……我明白了。我没有意识到字段是不可覆盖的;只有方法是。我将 String 字段视为一种方法。

标签: java nested relationship anonymous-types anonymous-class


【解决方案1】:

字段不可覆盖。如果一个类声明了一个名为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

因此,如果您修改演示以使用方法而不是字段,您将看到预期的结果。

【讨论】:

  • 啊,我明白了,谢谢!我对待这个领域就像对待一种方法一样。所以只是为了澄清匿名类是否扩展了用于定义它的类型?但是,因为它被定义为父类型,所以访问该字段将访问它的父实例。
  • @JonathanWhite:回复:第一个问题:是的。回复:第二个问题:如果我理解正确,那么 - 不完全正确。例如,System.out.println(new NestedClass() { String string = "Hello from anonymous class."; }.string); 将打印"Hello from anonymous class.",因为它从类型为匿名类的表达式中获取string。您的anonymousClass.string"Hello from nested class." 的原因是您的表达式anonymousClass 具有NestedClass 类型。你明白我的意思吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-02-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多