Question

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

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top