Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
216 views
in Technique[技术] by (71.8m points)

java - Why does the line marked with //1 print 57 instead of 39?

class X {
    protected int v = 0;

    public X() {
        v += 10;
    }

    public void proc(X p) {
        System.out.println(43);
    }
}

class Y extends X {
    public Y() {
        v += 5;
    }

    public void proc(X p) {
        System.out.println(57);
    }

    public int getV() {
        return v;
    }
}

class Z extends Y {
    public Z() {
        v += 9;
    }

    public void proc(Z p) {
        System.out.println(39);
    }
}

class Main {
    public static void main(String[] args) {
        X x = new Z();
        Y y = new Z();
        Z z = new Z();
        x.proc(z);// 1
        System.out.println(y.getV());
    }
}

From what I can understand,the method proc() is called on an object of type X that "holds" a type Z and at runtime JVM checks the object's type and overrides the method with the proc() method from Y.But the method parameter is of type Z,why doesn't it call the overloaded method from the Z class?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It happens because you don't override the method 'proc' in Z class. When you overriding the method, you can't use argument, which has a child class of original argument class. If you add @Override on Z.proc(Z p), your code will be not compiled.

Let's imagine that it is possible, then you can use some method from Z class during executing Z.proc(Z p).

class Z extends Y {
    public Z() {
        v += 9;
    }

    public void proc(Z p) {
        someActions();
        System.out.println(39);
    }

    private void someActions() {
        System.out.println("Some actions");
    }

}

Now when you executing

X x = new Z();
x.proc(new X());

What should happens? There is no 'someActions' method in the X class. How it should works? That's why Z.proc(Z p) doesn't override X.proc(X p). Class Z, has two different methods: Z.proc(Z p) and Y.proc(X p).

When you calling

X x = new Z();
x.proc(new Z());

JVM looks for closest overrided or original method with signature 'proc(X)' to Z class (because X class has 'proc(X)' method) finds it in Y class and executing Y.proc(x p). That's why you see '57' in output.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...