Let’s consider this example :
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();
}
}
How can I change this class to have 1 2 in output when calling getAttribute() and not 1 1
Something like a global variable, I tried the final keyword but I can’t set something using a Method.
You need to make the attribute
static.Members that are declared
staticwill be shared between all instances of the class.Also, for it to output
1 2you need to changeto
ideone.com demonstration