[英]covariant return types and primitives in Java
在 OCP 書中,我讀到有這個協方差規則:
給定一個繼承的返回類型 A 和一個覆蓋的返回類型 B,您可以將 B 的實例分配給 A 的引用變量而不進行強制轉換嗎? 如果是這樣,那么它們是協變的。 此規則適用於基本類型和 object 類型。
如果該規則適用於原始類型,並且我可以將 int 值分配給 long 變量而無需強制轉換(因此它們是協變的),那么為什么代碼無法編譯(協變返回類型)? 我認為這句話或我對它的理解有問題?
class Class1
{
long method()
{
return 1L;
}
}
class Class2 extends Class1
{
public static void main(String[] args)
{
int B = 1;
long A = B; // no cast
}
// @Override
// int method() { return 1; } // does not compile // 'method()' in 'B' clashes with 'method()' in 'A'; attempting to use incompatible return type
}
您的問題與類型轉換無關,但與 inheritance 無關。 您正在嘗試覆蓋方法並將返回類型更改為不兼容的類型。 這是不可能的,但如果是這樣,那將是非常危險的。 方法簽名,包括返回類型,是一種你不能違反的契約。 您的調用 class 取決於該合同,因此如果可以覆蓋原始類型,您最終可能會遇到一個簡單的問題,即您的調用 class 不知道實際的返回類型。 但是通常使用多態性,因此在編譯時,您必須依賴於您正在使用的引用類型的協定。 請參閱以下簡單示例(由於最后一行,無法編譯):
public class Class1 {
long method() {
return 3; //int, but cast before the value is returned
}
}
class Class2 extends Class1 {
public static void main(String[] args) {
int B = 1;
long A = B; // no cast
}
int method2() { //renamed to get this compiled
return 3;
}
}
class SimpleClass {
public static void main(String[] args) {
int i = 1;
long j = 2;
long l = i + j; //this compiles because int is implicitly cast to long
//int k = i + j; // This doesn't compile because long can't be cast
//implicitly to int
}
}
class Class3 {
void whatIsTheResult() {
Class1 class1 = new Class1();
Class1 class12 = new Class2(); //No problem due to polymorphism, both
//objects have the reference type Class1,
// but actually, class12 is of type Class2
Class2 class2 = new Class2();
long a = class1.method() + class2.method2(); //By contract, method
//returns a long, method2 returns an int
int b = class1.method() + class2.method2(); // Same contract, but long
//can't be 'cast down' to int, so doesn't compile
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.