您可以通过继承或使用接口来做到这一点,其中变量在父类中设置为常量。由于您正在扩展 JLabel,因此您应该在两个类上实现接口:
public interface MyInterface {
int someint = 9;
}
public class MyClass1 extends JLabel implements MyInterface {
//this class has access to `someint`
}
public class MyClass2 extends JLabel implements MyInterface {
// also has access to `someint`
}
编辑
由于您希望能够从不同的类更改相同的变量,因此您必须确保您没有更改副本并且正在更改相同的变量,因此您应该volatile
在变量上使用关键字来向 java 指示所有线程都应该检查更新之前的值。
现在您需要有一个单独的类,以便可以从其他类中创建实例来获取值。您必须使用static
关键字来确保为所有类实例保留一份副本。
public class MyVariableWrapper {
public static volatile int some_var = 9;
public void updateSomeVar(int newvar) {
some_var = newvar;
}
public int getSomeVar() { return some_var; }
}
现在其他两个类只是这样做:
public class MyClass1 extends JLabel {
MyVariableWrapper myVariableWrapper;
MyClass1() {
super();
myVariableWrapper = new MyVariableWrapper();
// now I have access to `some_var`
}
}
public class MyClass2 extends JLabel {
MyVariableWrapper myVariableWrapper;
MyClass2() {
super();
myVariableWrapper = new MyVariableWrapper();
// now I have access to the same `some_var` as MyClass1
}
// this is a wrapper method for your convenience
// since you don't like the excess code when accessing the variable
public int getSomeVar() {
return myVariableWrapper.some_var;
// or myVariableWrapper.getSomeVar();
}
public void setSomeVar(int newvar) {
myVariableWrapper.some_var = newvar;
// or myVariableWrapper.setSomeVar(newvar);
}
}
现在你可以这样做:
MyClass2 myClass2 = new MyClass2();
System.out.println(""+myClass2.getSomeVar());