在Java中添加实例变量后,静态方法/变量的行为会发生变化

时间:2013-04-12 00:43:03

标签: java inheritance static-methods static-members abstraction

这不是一个问题,而是一个问题。我有几个继承以下抽象类的类:

public abstract class PixelEditorWindow {
    protected static int windowHeight, windowWidth;

    public PixelEditorWindow() {
        setWindowSize();
    }

    protected abstract void setWindowSize();

    public static int getWindowWidth() {
        return windowWidth;
    }

    public static int getWindowHeight() {
        return windowHeight;
    }
}

我让每个类继承抽象方法setWindowSize,在那里设置它们的窗口大小,并设置这两个变量,如下所示:

protected void setWindowSize() {
    windowWidth = 400;
    windowHeight = 400;
}

完美无缺。但我还需要所有这些来跟踪它们现在包含的JFrame,所以我通过以下方式修改了这个类:

public abstract class PixelEditorWindow {
    protected int windowHeight, windowWidth;
    JFrame frame;

    public PixelEditorWindow(JFrame frame) {
        this.frame = frame;
        setWindowSize();
    }

    public JFrame getFrame() {
        return frame;
    }

    protected abstract void setWindowSize();

    public int getWindowWidth() {
        return windowWidth;
    }

    public int getWindowHeight() {
        return windowHeight;
    }
}

现在,所有继承的类都具有相同的窗口大小,这是最后实例化的任何类型的窗口。 我可以通过另一个继承了所有子类继承的类来修复它,但这比我想要的要糟糕。 编辑:刚才意识到我也做不到,但还有很多其他方法可以解决这个问题。为什么添加非静态实例变量可以解决所有问题?或者我想是一个更好的问题 - 为什么没有非静态实例变量允许这个工作?

1 个答案:

答案 0 :(得分:0)

“静态”表示班级的关联。

非静态意味着对象级别的关联。

基本上,我需要删除所有静态内容。当你知道为什么需要它时,可以使用“静态”。