Difference between static and global variable in Java
I am new to J开发者_如何学JAVAava programming. Can anyone tell what is the difference between global and local variable in Java?
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
Your question is a little confused since you refer to static/global in the title, and global/local in your question.
static
variables are tied to a class, and you will have one instance per class.
classes can have member variables, and you will have one instance per instance of that class.
Note that this is complicated further if you have multiple classloaders. In this scenario you can have multiple class definitions loaded, and consequently, possible multiple static variables.
In addition to the other (good) answers:
public class Person{
public static final int TOTAL_PERSONS = 100;
public static int numberOfLegs = 2;
private String firstname;
private String lastname;
public void setFirstname(String firstname){ ... }
...
}
Writing the following code:
Person foo = new Person();
foo.setFirstname("foo");
Person bar = new Person();
bar.setFirstname("bar");
// At this point foo and bar have different firstname, and both have 2 legs
Person.numberOfLegs = 4;
// At this point foo and bar have different firstname, and they both got a pair of 2 extra (bionic) legs
// Person.TOTAL_PERSONS is a 'constant' and has an unmodifiable value of 100
Note this is example code and should not be taken as good practice nor to have any sense. ;)
Global and static variables are very similar . The only difference being static variables may be public or private . A public static variable is a global variable in java .
Local variables are specific to a method or a class.Their scope is restricted to the specified method or class.
There are two types of methods. They are class methods
and object methods
. Class methods
are identified with the key word static
. Any method that does not have a key word static
is called an object method
. Either can be applied to a method or to a variable.
精彩评论