Was*_*RAR 1 java attributes share class
让我们考虑这个例子:
public class Shared {
    private int attribute;
    public Shared() {}
    public void incrementAttribute(int i) {
            attribute += i;
    }
    public int getAttribute() {
            return attribute;
    }
    public static void main(String[] args) {
            Shared s1 = new Shared();
            Shared s2 = new Shared();
            s1.incrementAttribute(1);
            s2.incrementAttribute(1);
            s1.getAttribute();
            s2.getAttribute();
    }    
}
如何1 2在调用时将此类更改为输出,getAttribute()而不是1 1
像全局变量,我尝试了final关键字,但我不能使用方法设置.
你需要创建属性static.
private static int attribute;
        ^^^^^^
声明的成员static将在该类的所有实例之间共享.
此外,为了输出1 2你需要改变
s1.incrementAttribue(1);
s2.incrementAttribue(1);
System.out.println(s1.getAttribute());
System.out.println(s2.getAttribute());
至
s1.incrementAttribue(1);
System.out.println(s1.getAttribute());
s2.incrementAttribue(1);
System.out.println(s2.getAttribute());