Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sharing class attributes in Java

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.

like image 877
Wassim AZIRAR Avatar asked Jul 26 '26 16:07

Wassim AZIRAR


2 Answers

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

like image 96
aioobe Avatar answered Jul 28 '26 04:07

aioobe


Make the attribute variable static.

like image 33
Petar Minchev Avatar answered Jul 28 '26 06:07

Petar Minchev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!