javatutelearn.com

Easy Learning


Home

Search Javatutelearn.com :



Instance variable Vs Local variable

  • Instance variables are defined in the class.
  • When local variable name is same as instance variable.
  • Then local variable hides instance variable.
  • See the following example:
class student {
    
	// followings are instance variables
        String name; 
		int rollno;
		String address;
		// In the following method, names of local variables (i.e. arguments in the method) are same as names of instance variables
		// In this case, when we try to access variables, then local variables will be accessed, instance variables can not be accessed.
		// Because local variables hide instance variables of the same name.
        public void setdata (String name, int rollno, String address)
        {
			
			
        }
}
  • Here local variables (name, rollno and address) have same name as instance variales names.
  • To resolve above problem, use this keyword.
  • Because, this keyword always has access to current object. (i.e. it will access the instance variables of the current object)
  • See the following example:
class student {
    
	// followings are instance variables
        String name; 
        int rollno;
		String address;
		
        public void setdata (String name, int rollno, String address)
        {
			// following is use of  this  keyword
			this.name = name;
			this.rollno = rollno;
			this.address = address;
			
        }
}
  • In the above program, this.name refers the instance variable (i.e.class variable) of the class student.
  • And name without this keyword, is local variable of the method setdata().
  • Similarly, this.rollno and this.address are instance variables of the class student.
  • And rollno and address without this keyword, are local variables of the method setdata().
Now see the full program:
public class student {
    
	// followings are instance variables
        String name; 
        int rollno;
		String address;
		
        public void setdata (String name, int rollno, String address)
        {
			// following is use of  this  keyword
			this.name = name;
			this.rollno = rollno;
			this.address = address;
			
        }
		public void dispdata(){
			// here, no need to use this keyword
			// because same name local variables are not present
		    System.out.println("Name is " + name);
			System.out.println("Rollno is "+ rollno);
			System.out.println("Address is "+address);
		}	
		
	public static void main(String args[])	{
            student s1 = new student();
            s1.setdata("Gargi",170067,"New Delhi");
            s1.dispdata();
            			   
	}
}

Output

Name is Gargi
Rollno is 170067
Address is New Delhi

Remember: Local variables hides Instance variables in the method.





© Copyright 2016-2024 by javatutelearn.com. All Rights Reserved.