This keyword in java, Why use this keyword in java
1. Tutorial4us.com
This keyword in Java
This keyword in Java - this keyword used always for represent reference of current object. this
keyword is used at two place at method level and at constructor level.
Using this with a Field
For example, the Area class was written like this
public class Area
{
public int x = 0;
public int y = 0;
//constructor
public Point(int a, int b) {
x = a;
y = b;
}
}
2. Tutorial4us.com
Using this with a Constructor
public class Area
{
public int x = 0;
public int y = 0;
//constructor
public Area(int x, int y)
{
this.x = x;
this.y = y;
}
}
Important points related to 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.
This keyword Example
class Rectangle
{
int length;
int breadth;
void setDiamentions(int ln,int br)
{
this.length = ln;
this.breadth = br;
3. Tutorial4us.com
}
}
class RectangleEx
{
public static void main(String args[])
{
Rectangle obj = new Rectangle();
obj.setDiamentions(20,10);
System.out.println("Length of Rectangle : " +obj.length);
System.out.println("Breadth of Rectangle : " + obj.breadth);
}
}
Output :
Length of Rectangle : 20
Breadth of Rectangle : 10
Whenever we define constructor then if the local parameter names and instance variable names are
same then local parameters hide the instance variables (members of class) by overriding it, so to
resolve this ambiguity "this" keyword is used.
class Demo
{
int a,b;
Demo(int a,int b)
{
this.a=a;
this.b=b;
}
}