[英]How do I use static field of subclass in super class method
I have a code on my super class that want WIDTH and HEGHT from subclass to calculate 我的超类上有一个代码,希望子类的WIDTH和HEGHT可以计算
public SuperClass{
public Vector2 getCenter(){
float x = this.position.x + WIDTH/2;
float y = this.position.y + HEIGHT/2;
return new Vector2(x, y);
}
public void setCenter(Vector2 position){
float x = position.x - WIDTH/2;
float y = position.y - HEIGHT/2;
setPosition(new Vector2(x, y));
}
}
I have to use static field of WIDTH and HEIGHT but it compilation error cause super class still don't know where is WIDTH and HEIGHT. 我必须使用WIDTH和HEIGHT的静态字段,但是它编译错误导致超类仍然不知道WIDTH和HEIGHT在哪里。 Can I have static field that overrided in subclass?
我可以在子类中覆盖静态字段吗?
You can't do that. 你不能那样做。 The whole point of polymorphism is that super classes know nothing about child classes!
多态的全部意义在于,超级类对子类一无所知 !
In other words: dependency flows "upwards" only. 换句话说:依赖关系仅“向上”流动。 A child class depends on its superclass, but not vice versa.
子类取决于其父类,但反之则不然。
If at all, you can do something like this: 如果有的话,您可以执行以下操作:
public abstract class SuperClass {
protected abstract int getWidth();
to then call getWidth() within your base class algorithms; 然后在基类算法中调用getWidth(); and your child classes then have to implement those methods - that is how you actually do proper OO design following the Open/closed principle .
然后您的子类必须实现这些方法-这就是您实际上遵循“ 打开/关闭”原理进行正确的OO设计的方式。
So, the solution here is: you step back and do some more reading on OO design; 因此,这里的解决方案是:您退后一步,对OO设计进行更多阅读; how to do it;
怎么做; and how it actually works with Java.
以及它在Java中的实际工作方式。 And for the record: you really want to stay way from using static - that is an abnormality in good OO design;
记录在案:您真的想远离使用静态方法 -在良好的OO设计中这是一个异常 。 and should only be used when you have really good reasons to do so!
仅在确实有充分理由时才使用!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.