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 want your help to understand why the program prints A::foo Anonymous::foo Anonymous::foo . Is this anonymous class a replacement for the former B? overrides its methods?
As I see it, it should go to the default constructor, run Foo-print "A :: foo", than run B goo, since it was correctly redefined, but now B goo is the same as in the Anonymous class, therefore he distinguishes this from B (which does nothing) and runs it foo, which is above foo, B, so it should print "Anonymous: foo". What am I wrong about?
Thank you very much.
source share