I have the following variable in a class named Example:
private static int number;
If I wanted to assign the variable a number using an outside class, which would I do?
1) Make the setter method in Example static so I can access it like this:
Example.setNumber(3);
2) or Make the setter method non-static so I create an object of Example to set the number
Example e = new Example()
e.setNumber(3);
What are the differences between the two and which one is the better way?
It is a static variable so you won't need any object of class in order to access it. It's final so the value of this variable can never be changed in the current or in any class.
Yes. By using reflection, you can access your private field without giving reference methods.
Any java object that belongs to that class can modify its static variables. Also, an instance is not a must to modify the static variable and it can be accessed using the java class directly. Static variables can be accessed by java instance methods also.
It is recommendable to use a static method in this case.
Why? Well, if you make it a non-static method, that would lead to the following suprising effect:
Example e1 = new Example();
Example e2 = new Example();
e2.setNumber(3);
e1.setNumber(5);
System.out.println(e2.getNumber()); // surprise! prints 5,
So even though you called the method on e1, e2 is also affected. The corresponding static example is much less surprising:
Example e1 = new Example();
Example e2 = new Example();
Example.setNumber(5);
System.out.println(Example.getNumber()); // prints 5, no surprise...
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