How do you define Global variables in Java ?
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
This way you can access them with
GlobalClass.x
andGlobalClass.s
There are no global variables in Java, but there are global classes with public fields. You can use static import feature of java 5 to make it look almost like global variables.
you can call anywhere you want:
You are better off using dependency injection:
Lots of good answers, but I want to give this example as it's considered the more proper way to access variables of a class by another class: using getters and setters.
The reason why you use getters and setters this way instead of just making the variable public is as follows. Lets say your var is going to be a global parameter that you NEVER want someone to change during the execution of your program (in the case when you are developing code with a team), something like maybe the URL for a website. In theory this could change and may be used many times in your program, so you want to use a global var to be able to update it all at once. But you do not want someone else to go in and change this var (possibly without realizing how important it is). In that case you simply do not include a setter method, and only include the getter method.