Variable Kinds – Local, Class and Instance Variables
Mainly used kinds Local, Class and Instance Variables are discussed here.
- Understanding the three main kinds instance, class and local variables.
static int x=1;
This is a class variable as it can only be defined once and all objects based on this can use it and modify it. It does need a static modifier.
This is an instance variable which can be used by any object (instance of the class) but it would take different memory space for different objects. So each instance will have different copy of this variable.
public static void main(String args)
This is a a local variable and this would be usable within the scope of given method. For e.g. the current method is main() method, so it can be used within main method.
VarKinds ob=new VarKinds();
Instance variable does need an object declaration, which is being done here.
The class variable (static) is printed here directly. This is possible because its name does not clash with any other local variable name. If it clashes, the this keyword is to be used (provided current method is non-static).
This is instance variable reference using the reference of object.
This is local variable reference
- Other these kinds the method argument variable, constructor argument variables, array initialisation variables and exception indication variables are also considered as different kinds. They may however be considered as local types only.
- The oracle documentation for variable kinds and other definitions can be seen at.
Suggested Filename(s): VarKinds.java