Global variables in Java

后端 未结 24 2090
青春惊慌失措
青春惊慌失措 2020-11-22 11:56

How do you define Global variables in Java ?

24条回答
  •  情深已故
    2020-11-22 12:42

    As you probably guess from the answer there is no global variables in Java and the only thing you can do is to create a class with static members:

    public class Global {
        public static int a;
    }
    

    You can use it with Global.a elsewhere. However if you use Java 1.5 or better you can use the import static magic to make it look even more as a real global variable:

    import static test.Global.*;
    
    public class UseGlobal {
        public void foo() {
            int i = a;
        }
    }
    

    And voilà!

    Now this is far from a best practice so as you can see in the commercials: don't do this at home

提交回复
热议问题