开发者

I expired some trouble with understanding Java polimorphism

public class XXX {

    @Test
    public void test() {
        B b = new B();
       开发者_如何学编程 b.doY();
    }
}



class A {
    public void doY() {
        XProcedure.doX(this);
    }
}


class B extends A {

    public void doY() {
        super.doY();
        XProcedure.doX(this);
    }
}


class XProcedure {

    public static void doX(A a) {
        System.out.println("AAAA!");
    }

    public static void doX(B b) {
        System.out.println("BBBB!");
    }
}

The output is

AAAA! BBBB!

And I wonder why?


Although XProcedure has two methods with the same name - doX, the two signatures are different. The first method gets an instance of class A as a parameter, and the second one gets an instance of class B.

When you call XProcedure.doX(this), the correct method is called according to the class of the passed parameter.

"AAAA!" is printed because of the super.doY() call.
"BBBB!" is printed because of the XProcedure.doX(this); call.

this differs in A's constructor from this in B's constructor for the reasons in Che's answer. Although A's contructor is called from within a B's constructor, in A's scope, the instance is of class A.


You called super.doY which is a method on B's superclass A.

All animals can talk.

A cat is an animal.

A cat talks and drinks milk.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜