java jls。可替换的。这是什么意思?
我正在阅读jls,我面临着以下问题:
return-type-substitutable
来自jls的片段
A method declaration d1 with return type R1 is return-type-substitutable for another method d2 with return type R2 iff any of the following is true:
If R1 is void then R2 is void.
If R1 is a primitive type then R2 is identical to R1.
If R1 is a reference type then one of the following is true:
--R1, adapted to the type parameters of d2 (§8.4.4), is a subtype of R2.
--R1 can be converted to a subtype of R2 by unchecked conversion (§5.1.9).
--d1 does not have the same signature as d2 (§8.4.2), and R1 = |R2|.
前两点显然是正确的
你能澄清一下吗
--R1, adapted to the type parameters of d2 (§8.4.4), is a subtype of R2.
--R1 can be converted to a subtype of R2 by unchecked conversion (§5.1.9).
--d1 does not have the same signature as d2 (§8.4.2), and R1 = |R2|.
谢谢
附言。 为路易吉·门多萨
interface Foo {
List<String> foo(String arg1, String arg2);
}
class Bar implements Foo {
@Override
public ArrayList<String> foo(String arg1, String arg2) {
//implementation...
return null;
}
public String foo(String arg1, String arg2, String arg3) {
//implementation...
return null;
}
}
它正在工作
我的问题的原因是——我想了解jls的以下短语:
If a method declaration d1 with return type R1 overrides or hides the declaration of another method d2 with return type R2, then d1 must be return-type-substitutable (§8.4.5) for d2, or a compile-time error occurs
规则:
If R1 is a reference type then **one of the following** is true:
...
--d1 does not have the same signature as d2 (§8.4.2), and R1 = |R2|.
...
代码:
interface Foo {
List<String> foo(String arg1, String arg2);
}
class Bar implements Foo {
@Override
public List<String> anotherName(String arg1, String arg2,Object obj) {
return null;
}
这是编译错误
R1==R2(List<String > == List<String>
)
d1=d2
我在哪里违反了规定
# 1 楼答案
让我们把它分成几部分:
首先,我们需要一个方法声明
d2
和一个返回类型R2
:现在,我们定义一个扩展
SomeClass
的类,它定义d1
并返回R1
这是如何编译的?因为
d1
是可替换为d2
的返回类型,这意味着R1
可以替换R2
作为返回类型。这也被称为covariant return type,并在Java Tutorials. Returning a Value from a Method中介绍。这得到了另一条规则的支持:这意味着所有这些方法都适用于覆盖
SomeClass#d2
:但这些都是无效的实现:
# 2 楼答案
让我们有这个界面
还有一个实现它的类
我们有:
Bar#foo
asd1
List<String>
将d1中的返回类型设置为R1李>Foo#foo
asd2
List<String>
将d2中的类型返回为R2李>这意味着
R1
可以是R2
的一个亚型,这意味着R1应该通过IS-a测试。因此,我们可以做到以下几点:这与泛型更相关。这意味着
R1
应该通过IS-A测试,即使它抛出了未检查覆盖的警告。因此,我们可以做到以下几点:这意味着超载: