开发者

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'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.


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


Using that kind of anonymous construction in fact creates a subclass of B. You have overridden B's methods with the ones you provide in the anonymous class so those will be used instead.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜