Home > DeveloperSection > Interviews > What is this in java?

Posted on    March-27-2015 12:21 AM

 Java Java 
Ratings:
 1 Answer(s)
  523  View(s)
Rate this:

Mayank Tripathi
Mayank Tripathi

Total Post:807

Points:4035
Posted on    March-27-2015 1:11 AM

 In java, this is a reference variable that refers to the current object.
  1. 1.this keyword can be used to refer current class instance variable.
  2. 2.this() can be used to invoke current class constructor.
  3. 3.this keyword can be used to invoke current class method (implicitly)
  4. 4.this can be passed as an argument in the method call.
  5. 5.this can be passed as argument in the constructor call.
  6. 6.this keyword can also be used to return the current class instance.

Without this:
  1. class Student10{  
  2.     int id;  
  3.     String name;  
  4.       
  5.     Student10(int id,String name){  
  6.     id = id;  
  7.     name = name;  
  8.     }  
  9.     void display(){System.out.println(id+" "+name);}  
  10.   
  11.     public static void main(String args[]){  
  12.     Student10 s1 = new Student10(111,"Karan");  
  13.     Student10 s2 = new Student10(321,"Aryan");  
  14.     s1.display();  
  15.     s2.display();  
  16.     }  
  17. }  

Using this:
  1. //example of this keyword  
  2. class Student11{  
  3.     int id;  
  4.     String name;  
  5.       
  6.     Student11(int id,String name){  
  7.     this.id = id;  
  8.     this.name = name;  
  9.     }  
  10.     void display(){System.out.println(id+" "+name);}  
  11.     public static void main(String args[]){  
  12.     Student11 s1 = new Student11(111,"Karan");  
  13.     Student11 s2 = new Student11(222,"Aryan");  
  14.     s1.display();  
  15.     s2.display();  
  16. }  
  17. }  


Don't want to miss updates? Please click the below button!

Follow MindStick