Core Java


This Keyword In Java :
  • this keyword used to refer current object.
  • this is always a reference to the object on which method was invoked.
  • this can be used to invoke current class constructor.
  • this can be passed as an argument to another method.
 Example:
public class Box {
Double width, height, dept;
public Box(double w, double h, double d ) {
              this.width = w;
              this.height = h;
              this.dept = d;
}
}
Here the this is used to initialize member of current object.
The this is used to call overloaded constructor in  Java. 
public class Car {
private String name;
public Car() {
this("BMW");   // overloaded constructor is called.
}
public Car(String n) {
this.name = n;    // member is initialized using this.
}
}
The this is also used to call Method of that class.
public void getName() {
      System.out.println("TechA2ZSolution");
}
public void display() {
      this.getName();
      System.out.println();
}
this is used to return current Object
public Car getCar() {
        return this;
}
1 2 3