WHAT IS THIS IN JAVA?

Samuel Fernandes

Total Post:38

Points:190
Posted by  Samuel Fernandes
Java 
 814  View(s)
Ratings:
Rate this:
  1. Mayank Tripathi

    Post:807

    Points:4035
    What is this in java?

     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. }  

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!