Documente Academic
Documente Profesional
Documente Cultură
this is a reference to the current object, within an instance method or a constructor the
object whose method or constructor is being called. We can refer to any member of the
current object from within an instance method or a constructor by using this.
this cannot be used with static methods.
1) The this keyword can be used to refer current class instance variable.
If there is ambiguity between the instance variable and parameter, this keyword resolves
the problem of ambiguity.
In General if we have a class instance variable x of a data type y and we have a method in
which we pass another variable x of same data type to it as a parameter the compiler
wont be able to understand which variable x we are referring to. So we use this.
Eg 1)
Class Point
//constructor
public Point(int x, int y)
{
x = x;
y = y;
}
public static void main(String args[]){
Point p=new Point(10,20);
System.out.println(p.x,p.y);
}
Ambiguity is created between class
instance x and parameter x (which x
should be assigned which value)
Eg2)
//constructor
public Point(int x, int y)
{
this.x = x;
this.y = y;
}
}
Here this.x refers to class
instance x and it is assigned
the value of parameter x
this.interest =
interest;
}
this.height = height;
this.width = width;
}
}
class ImplSquare
{
public static void main(String args[])
{
Square sObj = new Square(4,6);
System.out.println("Variable values of object : ");
System.out.println("Object height = " + sObj.height);
System.out.println("Object width = " + sObj.width);
}
}
Output
Variable values of object :
Object height = 4
Object width = 6
In the above constructor this is used in a constructor to invoke the constructor of same class
in case of constructor overloading. We can do this by using this keyword followed by the list
of parameters, it is similar to invoking a method but only from within a constructor and
whenever it is used, it has to be the first statement in the constructor.
void method1(){
System.out.println("method is invoked");
}
void method2(){
this.method1();
compiler does it for you.
}
void method3(){
method2();
System.out.println("method is invoked");
}
void method2(){
method1(this);
}
void method3(){
method2();
}
public static void main(String args[]){
CheckInvocation s1 = new CheckInvocation ();
s1.method3(); //method3 calls method2 and it invoked and calls method1
}
}
this.obj=obj;
}
void display(){
System.out.println(obj.data);//using data member of A class
}
}
class A{ int
data=10;
A(){
B b=new B(this);
b.display();
}
public static void main(String args[]){
A a=new A();
}
}
Output:10