dan*_*aze 5 java inheritance libgdx
问题很简单,但我不确定是否可以这样做......
如果我们有类似的课程
class A {
private int foo;
public A(int bar) {
this.foo = bar;
}
public A setFoo(int bar) {
this.foo = bar;
return this;
}
public int getFoo() {
return this.foo;
}
public void doSomething() {
this.foo++;
}
}
Run Code Online (Sandbox Code Playgroud)
我们可以看到它只是一个私有成员和一个setter/getter的类.有趣的是,为了允许方法链接,setter正在返回this.
所以我们可以这样做:
A a = new A(0);
a.setFoo(1).doSomething();
Run Code Online (Sandbox Code Playgroud)
这里的问题是当我尝试扩展该类时添加一些实现这样的接口的功能
class B extends A implements I {
public B(int bar) {
this.super(bar);
}
public void methodI() {
// whatever
}
}
Run Code Online (Sandbox Code Playgroud)
看起来没问题,直到我开始像这样使用它
B b = new B(1);
b.setFoo(2).methodI();
Run Code Online (Sandbox Code Playgroud)
因为setFoo实际上是返回一个实例A,而不是实例B,并且在A methodI中不存在...
任何解决方法?谢谢.
顺便说一句,我只是简单地编写了一个基本代码来理解,但如果你想了解更多,我只是想扩展一些libgdx的基本类(比如Math.Vector2,Math.Vector3)来实现Poolable.
B类可以覆盖方法setFoo并将返回类型更改为B,因为B是A的更具体的版本.重写的方法可以具有更具体的返回类型.例如
class B extends A implements I {
public B(int bar) {
this.super(bar);
}
public void methodI() {
// whatever
}
@Override
public B setFoo(int bar) {
this.foo = bar;
return this;
}
}
Run Code Online (Sandbox Code Playgroud)