在Java中添加实例变量后,静态方法/变量的行为会发生变化
与其说这是个问题,不如说这是个问题。我有几个类继承了以下抽象类:在Java中添加实例变量后,静态方法/变量的行为会发生变化,java,inheritance,static-methods,static-members,abstraction,Java,Inheritance,Static Methods,Static Members,Abstraction,与其说这是个问题,不如说这是个问题。我有几个类继承了以下抽象类: public abstract class PixelEditorWindow { protected static int windowHeight, windowWidth; public PixelEditorWindow() { setWindowSize(); } protected abstract void setWindowSize(); public
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;
}
}
我让每个类继承抽象方法setWindowsSize,在这里它们设置窗口大小,并设置这两个变量,如下所示:
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;
}
}
现在,所有继承的类都具有相同的窗口大小,这是上次实例化的任何类型的窗口。我可以通过让另一个类继承所有子类都继承的这个类来修复它,但这比我想要的更混乱。编辑:刚刚意识到我也不能这么做,但是有很多其他的方法来解决这个问题。为什么添加一个非静态实例变量会把一切都搞糟?或者我想问一个更好的问题——为什么没有一个非静态的实例变量就允许这样做呢?“静态”意味着类级别的关联
非静态表示对象级别的关联
基本上,我需要删除所有静态内容。稍后,当您知道为什么需要它时,请使用“static”。请展示
setWindowSize
的实现,以便我们可以看到它们如何与父类字段交互。变量一开始就不应该是静态的。你走对了,继续走。