简体   繁体   中英

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

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. 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; and your child classes then have to implement those methods - that is how you actually do proper OO design following the Open/closed principle .

So, the solution here is: you step back and do some more reading on OO design; how to do it; and how it actually works with Java. And for the record: you really want to stay way from using static - that is an abnormality in good OO design; and should only be used when you have really good reasons to do so!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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