In Java what is the relationship of an anonymous class to the type it is defined as?

我们两清 提交于 2019-12-11 01:59:14

问题


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);

    }
}

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


回答1:


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)
    }
}

prints

child
2
parent
2

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.



来源:https://stackoverflow.com/questions/21869294/in-java-what-is-the-relationship-of-an-anonymous-class-to-the-type-it-is-defined

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!