在Java中,匿名类与其定义的类型之间的关系是什么? [英] In Java what is the relationship of an anonymous class to the type it is defined as?

查看:86
本文介绍了在Java中,匿名类与其定义的类型之间的关系是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果将匿名类定义为接口的类型,则该匿名类将实现该接口,但是,如果将其定义为另一个类的类型(如下所示),则它似乎不会扩展该类(因为我被告知确实如此.

If the anonymous class is defined as the type of an interface then the anonymous class implements the interface, however if it's defined as the type of another class (as shown below) it doesn't seem to extend the class (as I was told it did).

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".

Here, if the anonymous class extended the nested class then the out put would be "Hello from anonymous class.", however when run the output reads "Hello from nested class."

推荐答案

字段不可覆盖.如果一个类声明了一个名为string的字段,并且子类也声明了一个名为string的字段,则存在两个单独的名为string的字段.例如,该程序:

Fields are not overrideable. If a class declares a field named string, and a subclass also declares a field named string, then there are two separate fields named string. For example, this program:

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,所以即使实际实例的运行时类型为Child,也要引用Parent中声明的字段.

because childAsParent has type Parent, so refers to the field declared in Parent, even though the actual instance has runtime-type Child.

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

So if you modify your demonstration to use a method rather than a field, you will see the results you were expecting.

这篇关于在Java中,匿名类与其定义的类型之间的关系是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆