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."
Fields are not overrideable. If a class declares a field named
string
, and a subclass also declares a field namedstring
, then there are two separate fields namedstring
. For example, this program:prints
because
childAsParent
has typeParent
, so refers to the field declared inParent
, even though the actual instance has runtime-typeChild
.So if you modify your demonstration to use a method rather than a field, you will see the results you were expecting.