Sunday, November 25, 2018

java this keyword

this keyword

  • 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, height, depth;
  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. Such as, this.width refers to the variable width of the current object that has invoked the constructor. width only refers to the parameter received in the constructor i.e the argument passed while calling the constructor.

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(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("Studytonight");
}

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

this is used to return current Object

public Car getCar()
{
 return this;
}
Share:

Related Posts:

0 comments:

Post a Comment

Contact Form

Name

Email *

Message *

Popular Posts

Blog Archive

Blog Archive

Hassan.mosmer1@gmail.com