Anonymous class, Inheritance and Overriding

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.

+4
source share
4 answers

Your question is not so clear, but let me say that the answer is exactly the same if, instead of an anonymous class extending B , you had a top-level class C extending B Nothing about anonymous classes behaves differently with respect to polymorphism and inheritance. When B calls the foo() constructor, the override version in the derived class is called — here is the anonymous class.

+4
source

I think the confusing thing here is that you have two foo methods. One of them is private, so it does not have the right to redefine, the other is publicly available, so it can be redefined. B calls foo in its constructor, but this is overridden by its subclass.

+4
source

The constructor calls A.foo (A :: foo) because it is private and therefore not overloaded. A.foo calls goo (), which was overridden by B and then anonymous, so you get Anonymous.goo -> Anonymous.foo (Anonymous :: foo). Then constructor B calls foo, which is overridden by Anonymous so (Anonymous :: foo)

+3
source

Using this kind of anonymous construct actually creates a subclass of B. You have overridden methods of B with those that you provide in the anonymous class, so they will be used instead.

+1
source

All Articles