Why is it a bad idea to use global variables?
I want to make an array of variables available for all of the classes to use. It will store key states, so it can’t be set as const (final).
Could you show me some other (proper) way of how to do this?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Because it breaks encapsulation. All code can access them and modify them.
If there is only one instance to be used by all your code, you can use a singleton:
Note that this sample is particularly not thread-safe – for improved implementation approaches, see Java Singleton Design Pattern