逆變方法給出像下面的情況:在此代碼調用Java中
interface Base { }
interface Derived extends Base{ }
interface OtherDerived extends Base{ }
class A {
void implementation(Derived stuff) {
// Implementation A
}
}
class B extends A {
// contravariant; does not override
void implementation(Base stuff) {
// Implementation B
}
}
方法調用被分派像這樣:
(new B()).implementation(derivedObject); // Ex. 1: calls A.implementation
(new B()).implementation(baseObject); // Ex. 1: calls B.implementation
(new B()).implementation(otherDerivedObject()); // Ex. 2: calls B.implementation
我一直想知道的是,爲什麼呢Java基本上像重載一樣處理逆變方法(B.implementation)(除了A.implementation和B.implementation的簽名沒有被覆蓋等價)。是否有一個故意的原因來調用最具體的方法簽名(如果是這樣,你會指出我在Java規範中明確闡述的位置?),還是僅僅是Java中如何實現重寫的意外結果? ?
等什麼?在你提供的例子中,'A.implementation'實際上從來沒有被調用過。 – radoh
我想知道你是如何得到這個結果「*(新B())。實現(derivedObject); /例1:**調用A.implementation ***」..類A和B不在層次結構中。所以,你說的是不可能的..可能你沒有提供正確的代碼.. – hagrawal
對不起,忘了提 - B延伸A.^_ ^編輯了這個帖子來修復這個漏洞。 –