Is it bad to declare an object like this
public static GUI g = new GUI();
or should I avoid creating a public object when I want multiple methods to be able to use the same object?
Yes, it is generally bad to expose an object as a public static variable, because everybody has a write access to it. Making the variable final make it slightly better, but the best solution would be to make your variable private, and provide a static getter.
Static state is generally considered untestable, and bad. Every static object is an implicit input to everything you're trying to test, and tests are all about controlling the inputs and experimenting how your methods behave in response to precise parameters.
Instead, you should pass an explicit reference to the GUI object to every class that needs it. There are a number of ways to simplify the bookkeeping involved; typically involving dependency injection.
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