global variables in Java

There are no global variables in Java in the meaning of variables which would be valid in the whole program.

There are

  • class variables: These are most similar to what are called „global“ variables in other languages. They are declared inside a class with the static keyword. There is only one variable for the whole class. (If the class would be loaded again with another classloader, this new class would have new variables, of course.)

    They should be used prefixed with the class: MyClass.varName. Inside of the class you also can let the prefix away, and you also could use them prefixed with an object of that type (but this is discouraged).

  • instance (or object) variables: These are what you have in your example: anything declared inside a class (and outside of any method/constructor/block) without the static keyword is a instance variable. For each object of the containing class (which includes objects of any subclasses of this class) there is exactly one variable. (From the „state“ view, one could say an object consists of all its instance variables + an identity.)

    They are used prefixed by an object (of the right type): myObject.varName. Inside of non-static methods of this class you can use them unprefixed (this is then referring to the variables of the current object).

  • local variables: These are all variables declared inside of a method or a constructor (or block). They exist once for each invocation of this method, and cease to exist after the method finished. They can only be accessed from inside this method, not from methods called from there.

    Special cases of these are method/constructor parameters and catch-block-parameters.

  • array elements: Every element of an array is a variable of the same type. They can be used everywhere where one has a reference to this array (often in one of the other types of variables).

via: Java only allowing global variables to be static? – Stack Overflow.

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert.