- If the value of a variable is varied from object to object such
type of variables are called instance variables
- For every object a seperate copy of instance variable will be created
- The scope of instance variables is exactly same as the scope of
the objects. Because instance variables will be created at the time of
objects creation & destroy at the time of objects destruction
- Instance variables will be stored as the part of objects
- Instance variables should be declare with in the class directly, But outside of any
method or block or constructor
- Instance variables cannot be accessed from static area directly we can
access by using object reference. But from instance area we can access instance members directly
Ex:-
class Test{
int x=10;
public static void main(String args[]){
Syste.out.println(x); -----------> compile time error
Test t=new Test();
System.out.println(t.x);------->10
}
public void m1(){
System.out.println(x);---------->10
}
}
- For the instance variables it is not required to perform initialization explicitly
JVM will provide default values
For Example:-
class Test{
String s;
int x;
boolean b;
public static void main (String args[]){
Test t=new Test();
System.out.println(t.s); ---------> null
System.out.println(t.x); -----------> 0
System.out.println(t.b); --------------> false
}
}
- Instance variables also known as " Object level variables" or "attributes".