Global variables in Java

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

How do you define Global variables in Java ?

24条回答
  •  悲哀的现实
    2020-11-22 12:22

    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.

    public class Global{
        private static int var = 5;
    
        public static int getVar(){
            return Global.var;
        }
    
        //If you do not want to change the var ever then do not include this
        public static void setVar(int var){
            Global.var = var;
        }
    }
    

提交回复
热议问题