- #1
- 28,950
- 4,245
I was forced into learning Java. I feel reasonably fluent in C++, so the main problem is with the differences between the way languages are designed.
There are no global variables in Java. However, I need one - or at least some equivalent. I have something like a database object that I want to have access to in many classes in my program. In C++ I would just make it a global variable. In Java I can't. ATM I can think of three ways of dealing with the situation:
1. Make the object a static variable in my main class. I feel like it's a hack, not a serious solution.
2. Define all my classes inside of the main class. Inconvenient nonsense.
3. Pass the object to all methods that may need an access to it, or at least pass it to constructors, so that every object can save a local reference to the database object. Makes the code bloated, or/and it means I need to add constructors even in all places were otherwise default would be enough.
Other ideas? Or perhaps I am approaching it completely wrong, and that's just not the way you program in Java?
There are no global variables in Java. However, I need one - or at least some equivalent. I have something like a database object that I want to have access to in many classes in my program. In C++ I would just make it a global variable. In Java I can't. ATM I can think of three ways of dealing with the situation:
1. Make the object a static variable in my main class. I feel like it's a hack, not a serious solution.
2. Define all my classes inside of the main class. Inconvenient nonsense.
3. Pass the object to all methods that may need an access to it, or at least pass it to constructors, so that every object can save a local reference to the database object. Makes the code bloated, or/and it means I need to add constructors even in all places were otherwise default would be enough.
Other ideas? Or perhaps I am approaching it completely wrong, and that's just not the way you program in Java?