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.
Your question isn't all that clear, but let me just say that the the answer would be exactly the same if instead of an anonymous class extending B
, you had a top-level class C
extending B
. Nothing about anonymous classes makes them behave differently with respect to polymorphism and inheritance. When B
's constructor calls foo()
, the overriding version in the most-derived class -- here the anonymous class -- is invoked.
I think the confusing thing here is you have two foo methods. One is private so it's not eligible for overriding, the other is public so it can be overridden. B is calling foo in its constructor but that's overridden by its subclass.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With