fastread homefastrread library fastread menu

Java : This keyword

Tutorial by:Arena Buocel      Date: 2016-04-29 23:27:10

❰ Previous Next ❱

  • this keyword is used to refer to 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 :

class Box
 {
  Double width, weight, dept; 
  Box (double w, double h, double d)
  {
   this.width = w;
   this.height = h;
   this.depth = d;
  }
}

Here the this is used to initialize member of current object.


The this is used to call overloaded constructor in java

class Car
{
 private String name;
 public Car()
 {
  this("BMW");    //oveloaded constructor is called.
 }
 public Car(Stting 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("Studytonight");
}

public void display()
{
 this.getName();
 System.out.println();
}

this is used to return current Object

public Car getCar()
{
 return this;
}

❰ Previous Next ❱


Java

Submit Your Thought, Tutorial, Articls etc.

Submit Your Information India's Number one online promotion website