【发布时间】:2020-12-05 06:44:15
【问题描述】:
我正在使用两个具有相同方法签名的接口并尝试在名为 Parent 的类中实现 和孩子。但是,我很困惑为什么协变返回类型在这里不起作用。
interface First
{
public long show();
}
interface Second
{
public int show();
}
abstract class Parent implements First,Second
{
public long show(){
return 10L;
}
}
class Child extends Parent
{
public int show(){
return 10;
}
}
I get the following errors after compilation
error: show() in Parent cannot implement show() in First
public int show(){
^
return type int is not compatible with long
error: show() in Child cannot implement show() in Second
public long show(){
^
return type long is not compatible with int
^
return type long is not compatible with void
But why int is not compatible with long?
【问题讨论】:
-
“协变返回类型仅适用于非原始返回类型。” - 参见例如tutorialspoint.com/Covariant-return-types-in-Java
-
你查看this 的帖子了吗?
-
@Swati 这个帖子没有涵盖我的问题
-
不要完全更改现有问题。如果您有新问题,请创建一个新问题。
-
强烈反对更改现有问题的规则。该项目的目标是创建一个问题及其答案的数据库。通过更改问题而不是创建新问题,您正在颠覆这一点。另外,在你把问题改得这么彻底之后,你原来的问题的答案会显得很傻。
标签: java