简体   繁体   English

Java:与实现接口的类不兼容的返回类型

[英]Java: incompatible return type with a class implementing an interface

I have an interface and an implementation:我有一个接口和一个实现:

// there are things
public interface Thing { /* ... */ }
// balls are things
public class Ball implements Thing { /* ... */ }

I have another interface and another implementation:我有另一个接口和另一个实现:

// a dog can fetch any thing
public interface Dog {
    public Thing fetch();
}
// a shepherd can fetch only a ball
public class Shepherd implement Dog {
    public Ball fetch() { /* ... */ }
}

This is fine.这可以。

But now I want to use Ball as a parameter of a parametrized class:但现在我想使用Ball作为参数化类的参数:

public interface Dog {
    public List<Thing> fetchList();
}
public class Shepherd implement Dog {
    public List<Ball> fetchList() { /* ... */ }
}

Java doesn't allow me to do so, it says I'm attempting to use incompatible type. Java 不允许我这样做,它说我正在尝试使用不兼容的类型。

At the same time this construction works without any issues:同时,这种结构没有任何问题:

public class Shepherd implement Dog {
    public List<Thing> fetchList() { /* ... */ }
}

Why does Java allow me to use an implementation of an interface as the returning value's definition, but doesn't allow me to use it as the parametrized class' parameter?为什么 Java 允许我使用接口的实现作为返回值的定义,但不允许我将它用作参数化类的参数?

Thanks in advance!提前致谢!

Because not every Thing is a is a Ball因为不是每一个Thing是一个Ball

You can try to parametrize super type like this您可以尝试像这样参数化超类型

public interface Dog<T extends Thing> {
    public List<T> fetchList();
}

public class Shepherd implement Dog<Ball> {
    public List<Ball> fetchList() { /* ... */ }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM