Tutoriallearn.com

Easy Learning


Home

Search Tutoriallearn.com :



Java this keyword

Keyword this refers the current object.
if you want to refer the object on which a method is invoked. Then use this keyword.
Consider the following example

class student {
    
        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 getdata ()
        {

            System.out.println ("Your name is " + name);
			System.out.println ("Your roll no is " + rollno);
			System.out.println (" Your address is " + address);
		}

}

class demostudent {

   public static void main (String args[])
		{
            student s1 = new student();
            s1.setdata("Amit",123456, "Delhi");
			s1.getdata();
		}

} 

Output

Your name is Amit
Your roll no is 123456
 Your address is Delhi

Explanation of the program

  • setdata() method of student class has arguments name same as class variables name.
  • Within setdata() method , compiler is confused in distinguishing the difference between arguments recevied and class variables.
  • see the following:
  •  public void setdata (String name, int rollno, String address)
            {
    			// compiler will be confused here, because of same names
    			name = name;
    		    rollno = rollno;
    			address = address;
            }
    
  • To resolve above the problem, this keyword is used to refer the class variables (i.e. referring the current object which invokes the setdata() method.





© Copyright 2016-2025 by tutoriallearn.com. All Rights Reserved.