Objective
Opening Ming Yi: Java is OOP programming and there is no concept of global variables.
Why use global variables
You want to be able to refer to a member variable that is not defined in this class in another class, there are two methods, one is parameter passing (this is most consistent with OOP programming idea, but this will increase the number of parameters, and if this parameter is used after a few linear calls, it will greatly increase the programming burden), Another one is defined in a variable or class (which increases the coupling between classes and requires the introduction of global classes or). Here we discuss this kind of.
Interface implementation
Public Interface globalconstants{ = "Chilly Billy"; = "Ten Chicken head Lane";} Public class Implements globalconstants{ public Globalimpl () { System.out.println (name);} }
In "Effictive Java" 第4-19篇: Use interfaces-Define types "The constant interface pattern is a poor use of interfaces. "There is another sentenceConstant interface Antipattern. jdk1.5+: You can use the static import for your global variables, implementing are not needed. All parties have indicated that this method is undesirable. Also: The other thing is, I often in the tangled global variable is defined in class or defined in the interface, after looking at the Java official definition of the global variable, I understand, or the definition in the class is more appropriate, Because although the definition in interface can do the same function and still less write a lot of final static modifiers, but this is not in line with the interface definition of the original intention. Interface more is used to regulate or formulate behavior. Class
It is not recommended to use dependency injection at first, such as the following:
Public class Globals { publicint A; Public int b;} Public class usesglobals { privatefinal Globals Globals; Public usesglobals (Globals Globals) { this. Globals = Globals; }}
Finally, we use the most official approach (note the import static used):
Package test; class globalconstant{ publicstaticfinal String CODE = "CD";} Import Static test. globalconstant;publicclass test{ private String str = Globalconstant.code;}
Problems with global variables <Java>