Sometimes a method will need to refer to the object that invoked it. To allow this, Java
defines the this keyword. this can be used inside any method to refer to the current object.
// A redundant use of this.
Box(double w, double h, double d) //constructor
{
this.width = w;
this.height = h;
this.depth = d;
}
Box ob1 = new Box(2,3,4);
// this refer to object ob1 here
Box ob2 = new Box(5,6,7);
//this refer to object ob2 here
void display( ) // method
{
System.out.println(this.width+” “+this.height+” “+this.depth);
}
ob1.display();
// this refer to object ob1 here.
It is illegal in Java to declare two local variables with the same name inside the same or
enclosing scopes. When a local variable has the same name as an instance variable, the local
variable hides the instance variable.
Because ‘this’ refer directly to the object, we can use it to resolve any name space collisions
that might occur between instance variables and local variables.
// Use this to resolve name-space collisions.
Box(double width, double height, double depth)
{
this.width = width;
this.height = height;
this.depth = depth;
}
Comments
Post a Comment