Two uses of the this keyword are
class Student { //instance variable name String name; Student(String name) //parameter variable name { name=name; //wrong , creating ambiguity this.name=name; //Correct, this.name is instance variable // and name is local parameter variable } public static void main(String[] args) { Student ob=new Student("Rohit"); System.out.println("Name Is :"+ob.name); } }
To pass the current object as a parameter to another method or constructor
public class MyDate { private int day = 1; private int month = 1; private int year = 2000; public MyDate(int day, int month, int year) { this.day = day; this.month = month; this.year = year; } public MyDate(MyDate date) { this.day = date.day; this.month = date.month; this.year = date.year; } public MyDate addDays(int moreDays) { MyDate newDate = new MyDate(this); newDate.day = newDate.day + moreDays; // Not Yet Implemented: wrap around code... return newDate; } public String toString() { return "" + day + "-" + month + "-" + year; } }
The this() constructor call can be used to invoke the current class constructor (constructor chaining). This approach is better if you have many constructors in the class and want to reuse that constructor.
class Student{ int id; String name; Student() { System.out.println("default constructor is invoked"); } Student(int id,String name) { this ();//it is used to invoked current class constructor. this.id = id; this.name = name; } void display() { System.out.println(id+" "+name); } public static void main(String args[]) { Student ob1 = new Student(101,"Rahul"); Student ob2 = new Student(102,"Rohit"); ob1.display(); ob2.display(); } }
Output: default constructor is invoked default constructor is invoked 101 Rahul 102 Rohit
this keyword that you return as a statement from the method
class Demo{ Demo getDemo(){ return this; } void show() { System.out.println("Welcome"); } } class Demo1 { public static void main(String args[]) { new Demo().getDemo().show(); } }