For the sake of discussion let’s have the following class
/**
* Simple java class for instance, local and class variable demonstration
*
* @author Practical IT <info@thepracticalit.com>
*
*/
public class Java {
//instance variables are those outside of methods in class
//they accessible in non-static methods in the class.
private int iAmInstanceIntVariable;
//static variables don't need object to be accessed, just class
private static int iAmClassVariable = 200;
public float iAmInstanceMethodReturningNothing() {
//examples of local variables that are accessed within the method/function only
int iAmLocalVariableAccessibleInMethodOnly = 90;
float iAmLocalFloatVariableAcessibleInThisMethodOnly = 120.9f;
//their sum can be returned but the variables are accessed in this method only.
return iAmLocalFloatVariableAcessibleInThisMethodOnly+ iAmLocalVariableAccessibleInMethodOnly;
}
public int iAmStaticMethodReturningInt() {
int iAmLocalintInitializedWithFive = 5;
return iAmLocalintInitializedWithFive;
}
public void setInstanceInt(int iAmClassVarible) {
this.iAmInstanceIntVariable = iAmClassVarible;
}
public int getInstance() {
return this.iAmInstanceIntVariable;
}
public static int getStaticVariable() {
//this.iAmInstanceIntVariable = 4; this is invalid static method can't access instance variable.
return iAmClassVariable;
}
public static void main(String[] a) {
//create an instance, java is instance of Java class
Java java = new Java();
java.setInstanceInt(23); //object can access method.
System.out.println(java.getInstance());//get instance is accessed only from 'instance'
System.out.println(Java.iAmClassVariable);//this is what class variable mean, it is accessed from the class not from instance
//iAmStaticMethodReturningInt is a method returning a local variable's value
System.out.println(java.iAmStaticMethodReturningInt()); //method is also accessed from instance only
System.out.println(Java.getStaticVariable()); //method that is accessed only from the class - static
}
}
*This is a light version of definition. There could be cases more complex implementation may override the common behavior.
Instance Variables
- Declared outside of the methods but inside the class.
- Can be accessed in the non-static methods of the class or children based on the right access modifier.
- Can have private, public, protected.. access modifiers
- declared as access modifier data type variable name [= value]
- Are available/visible for the “instance” of the class. Different objects/instances can have different values for the variables.
Static Variables / Class variables
- Declared outside of the methods but inside the class.
- Declared as access modifier static data type variable name [=value]
- Accessed through the class and not through “instance”
- All objects have access/visibility to the variable and see the same value
Local Variables
- Declared within methods of the class, including the constructor.
- Visibility/access is limited to the method that declared it.