r/javahelp • u/Dead-Stroke54 • Jul 28 '20
Warning when accessing static variable from a different class
Hello, I am doing a project where a class variable gets updated and that new value needs to go into a different class. The only way i was able to do this was by making it a static variable in its original class and then referencing it by className.staticVariable , but this gives me warnings in the IDE despite it working fine. I was wondering if theres a way to accomplish the same thing but without getting the warning, or if it is fine as it is. The warning reads : The static field className.staticVariable should be accessed in a static way. I have tried getting it to work by using object of the classes involved but these attempts just gave me overflow errors. Any help would be appreciated
1
u/DMLooter Jul 28 '20
If your IDE is giving that warning it means you are actually using an object to refer to the static variable, not the actual name of the class.
1
u/Dead-Stroke54 Jul 28 '20
Wow im really stupid. I tried this before and saw that I get a grey error message. Forgot that meant error fixed. Feel stupid.
1
u/DMLooter Jul 28 '20
All good! I’ve done the same thing many times, glad you were able to figure it out.
1
u/sinistergroupon Jul 29 '20
I know you already got your answer but to take a step back why is time static to begin with? You seem to change it on every command. Shouldn’t that be an instance variable?
1
u/Dead-Stroke54 Jul 29 '20
The reason I cant is because the method is called without an object I think. So it tries to set an instance variable of no onject
1
u/sinistergroupon Jul 29 '20
Not everything you’re saying makes sense. onCommand definitely needs an instance to run and fire on the events. You could get into some weird timing issues with the code you have. It doesn’t smell right but I don’t have enough context as to what’s happening here.
1
u/Camel-Kid 18 year old gamer Jul 28 '20
to avoid using static variables, just pass in parameters to constructor and use the good ole getter/setters. Taht's what is so great about OOP design