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.
private static int attribute;
^^^^^^
Members that are declared static will be shared between all instances of the class.
Also, for it to output 1 2 you need to change
s1.incrementAttribue(1);
s2.incrementAttribue(1);
System.out.println(s1.getAttribute());
System.out.println(s2.getAttribute());
to
s1.incrementAttribue(1);
System.out.println(s1.getAttribute());
s2.incrementAttribue(1);
System.out.println(s2.getAttribute());
ideone.com demonstration
Make the attribute variable static.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With