我有一个案例,我有这样的情况:
public abstract class Base{
private Base sibling;
public Base( Base sibling ){
this.sibling = sibling;
}
public Base getSibling(){
return this.sibling;
}
}
public class ChildA extends Base{
private ChildB brother;
public ChildA(){
this.brother = new ChildB( this );
}
public ChildB getBrother(){ return this.brother }
public void methodA(){ ... }
public void methodB(){ ... }
}
public class ChildB extends Base{
public childB someMethodX(){ ... }
public childB someMethodY(){ ... }
}
现在我需要它,以便在做类似的事情时:
var child = new ChildA()
.getBrother()
.someMethodX()
.someMethodY()
.getSibling()
.methodA()
.methodB()
.getSibling()
将我返回到 ChildA
的范围。但目前它似乎返回了一个 Base
实例,并给我一个错误,指出 methodA()
在类 Base
中不存在。
我已经研究了一些 GenericTypes 的情况,这可能是我在这种情况下想要的,但到目前为止我一直在努力实现它。任何示例/指针/链接将不胜感激。
谢谢。
最佳答案
这不起作用,因为 methodA
是在 ChildA
中定义的,但 getSibling
返回 Base
引用。尽管此 Base
引用恰好指向 ChildA
对象,但您应该执行显式转换或泛化 Base
类型。
在这种特殊情况下,您可以简单地重写getSibling
:
class ChildB extends Base {
public ChildB(ChildA sibling) {
super(sibling);
}
@Override
public ChildA getSibling() {
return (ChildA) super.getSibling();
}
}
如果有很多像 ChildB
这样的类,这将无法很好地扩展。此外,ChildB
仅限于包含 ChildA
,因为它是同级。
编辑:
it may not always be childB
好吧,假设您不需要 Base
类是通用的,您可以将其替换为:
class ChildB <T extends Base> extends Base {
public ChildB(T sibling) {
super(sibling);
}
@Override
@SuppressWarnings("unchecked")
public T getSibling() {
return (T) super.getSibling();
}
}
您可以按如下方式实例化它:
brother = new ChildB<ChildA>(this);
关于java - 通过 child build 者,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26005396/