What is Instance variable and this keyword in JAVA


          In java, everything is class and objects. object is  an instance of a  class.For a class, many objects can be created.The variables defined in the class outside the method is called instance variables as it is related to object. i.e. instance of the class.The value of the variables will change according to the object. Hence these variables are  called instance variables.
Consider the below example.

 class SampleClass{
     int  iVar;

  //Setter and getter methods to set and get the value of iVar  - will discuss in upcoming posts  
    public void setValue(int iVar){
        this.iVar=iVar;
}
public int getValue(){
        return iVar;
}

public static void main(String args[]) {
                 SampleClass exp=new SampleClass();
                 exp.setValue(10);
                 exp.add();
                 SampleClass exp1=new SampleClass();
                 exp1.setValue(15);
                 exp1.add();
}
   void add(){
                  int b=iVar+5;
                  System.out.println("Value of b is "+b );
   }
}
 Output:
         Value of b is 15  // when exp object is calling the add method. Here the value of a is 10
         Value of b is 20  // when exp1 object is calling the add method. Here the value of a is 15

       In the above program,for the SampleClass,two objects  were created .ie.exp and exp1.setValue method  is used to set the value for the iVar and getValue  method is used to get the value of the iVar.Here iVar is the instance variable.
       For exp object,the value of the variable is set to 10 and for exp1 object,the value of the variable is set to 15. Hence when the add() method is called ,the value of b is changed based on which object is calling the add() method. The value of instance variable [iVar] will change with respect to object.

"this" keyword

    "this" keyword indicates the  instance variable of the object  which is instantiated.If exp object is calling the setValue method then the value passed as a parameter will be set to instance variable iVar correponding to exp object using "this" keyword."this" refers to current object."this" keyword is used to resolve the ambiguity between instance variables and local variables.
In the above example we have discussed, consider the setValue() method.

public void setValue(int iVar){
        this.iVar=iVar;
}
    Here this.iVar refers the variable of the object i.e. instance variable .If in the setValue method ,"this" keyword is not used as below, the value will be set to 0[ zero].

        public void setValue(int iVar){
         iVar=iVar;
 }

     

Previous
Next Post »