public class A {
public A() {
foo();
}
private void foo() {
System.out.print("A::foo ");
goo();
}
public void goo() {
System.out.print("A::goo ");
}
}
public class B extends A {
public B() {
foo();
}
public void foo() {
System.out.print("B::foo ");
}
public void goo() {
System.out.print("B::goo ");
}
public static void main(String[] args) {
A b = new B() {
public void foo() {System.out.print("Anonymous::foo ");}
public void goo() {((B)this).foo();}
};
}
}
I'd like your help with understanding why does the program print A::foo Anonymous::foo Anonymous::foo
. Is this anonymous class replace the former B? overrides its methods?
As I see it, it should go to A's default constructor, run A's foo- print "A::foo", than run B's goo, since it was properly overrided, but now B's goo is the one in the Anonymous class, so it casts this to B (Which does nothing), and run its foo, which is the foo above, of B, so it should print "Anonymous:foo". What do I get wrong?
Thanks a lot.