Difference between static and global variable in Java

后端 未结 5 870

I am new to Java programming. Can anyone tell what is the difference between global and local variable in Java?

5条回答
  •  粉色の甜心
    2020-12-18 18:02

    There is no concept of global variable in the Java programming language. Instead, there are class and member attributes. Class attributes are marked with the static keyword, meaning that they can be accessed without instanciation, while member attributes are tied to an instance of a class.

    Little example:

    public class Person{
        public static final int TOTAL_PERSONS;
    
        private String firstname;
        private String lastname;
    
        public void setFirstname(String firstname){ ... }
        ...
    }
    

    With this class, I can use Person.TOTAL_PERSONS, but not Person.firstname. To get/set the first name (without mentionning getters/setters which you'll probably soon discover), you first need to create an instance of that class:

    Person p = new Person();
    p.setFirstname("foo");
    

    Finally, note that it's possible to create what other languages refer to as global variables. For instance, you can use the Singleton pattern, but anyway, global variables shouldn't be used without valid reasons: check this page

提交回复
热议问题