Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to modify private static variable through setter method

Tags:

java

static

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?

like image 474
Sujen Avatar asked Jul 26 '11 15:07

Sujen


People also ask

Can private static variables be changed?

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.

Can we modify private variable in Java?

Yes. By using reflection, you can access your private field without giving reference methods.

Can we modify static variable in Java?

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.


1 Answers

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...
like image 168
amarillion Avatar answered Oct 01 '22 17:10

amarillion