[英]The return types are incompatible for the inherited methods
class A {
public A get() { }
}
class B extends A {
}
The return types are incompatible for the inherited methods, how to solve this problem ? 返回类型与继承方法不兼容,如何解决这个问题?
From JDK 5, Java allow you to alter the return type of an overridden method, as long as the new type is a subclass of the original one. 从JDK 5开始,Java允许您更改被重写方法的返回类型,只要新类型是原始类型的子类。 This is called covariant return type . 这称为协变返回类型 。 Following code will compile correctly: 以下代码将正确编译:
class A {
A get() {
return new A();
}
void sayHello(){
System.out.println("Hello");
}
}
class B extends A {
@Override
B get() {
return new B();
}
void sayGoodbye(){
System.out.println("Goodbye");
}
}
class Test{
void check(){
B two=new B();
two.get().sayGoodbye();
}
}
Remember that the return type of the overridden method should be a subclass of the return type, to allow you to call the method on A variables and get a valid A object (which is infact a B instance): 请记住,重写方法的返回类型应该是返回类型的子类,以允许您在A变量上调用方法并获取有效的A对象(实际上是B实例):
void check(){
A two=new B();
A copy=two.get();
copy.sayHello();
}
Use generics: 使用泛型:
class A<T extends A> {
public T get() { }
}
class B extends A<B> {
}
B b = new B();
B got = b.get();
I'm assuming you want to write something like B b = new B().get();
我假设你想写一些像B b = new B().get();
without explicit typecasting like Nikita Beloglazov suggests, though that's not an idiom that Java supports well. 没有明确的类型转换,如Nikita Beloglazov建议,尽管这不是Java支持的成语。 Eugene's answer works well enough, though that still involves a cast to T
and generates an ugly compiler warning besides. Eugene的答案运作得很好,尽管这仍然涉及对T
的强制转换并且还会产生一个丑陋的编译器警告。 Personally, I would write code more like the following: 就个人而言,我会编写更像以下代码:
class A {
private A() {}
public A get() {
return new A();
}
}
class B extends A {
private B() {}
@Override
public A get() {
return new B();
}
public B getB() {
return (B) get();
}
}
You still can't do B b = new B().get();
你仍然不能做B b = new B().get();
, but you can do B b = new B().getB();
,但你可以做B b = new B().getB();
, which is just as easy and a bit more self-documenting anyways, since you already know you want a B
object, not just any A
object. ,无论如何,这都是一样简单和自我记录,因为你已经知道你想要一个B
对象,而不仅仅是任何A
对象。 And A a = new B().get();
并且A a = new B().get();
would create a B object, albeit one that only has access to the methods declared in A
. 会创建一个B对象,尽管只能访问A
声明的方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.