this Keyword
this is a keyword that refers to the object of present class. Generally, we write instance variables, constructors and methods in a class. Whenever data members of a class and formal parameters of a method or constructor is existing with same name then system will get confused to overcome this problem “this.†can be useful.
No need of this keyword
class Test
{
int a=10;
int b=20;
void add(int i,int j)
{
System.out.println(a+b);
System.out.println(i+j);
}
public static void main(String[] args)
{
Test t=new Test();
t.add(100,200);
}
};
Output :
this keyword is required
class Test
{
int a=10;
int b=20;
void add(int a,int b)
{
System.out.println(a+b);
System.out.println(this.a+this.b);
}
public static void main(String[] args)
{
Test t=new Test();
t.add(100,200);
}
}
Output :
to call the current class mehods we have to use this keyword
class Test
{
void m1()
{
this.m2(); //m2() both are same
System.out.println("m1 method");
}
void m2()
{
System.out.println("m2 method");
}
public static void main(String[] args)
{
Test t=new Test();
t.m1();
}
};
Output :
output:m1 method,,m2 method
In side the Constructors this keyword must be first statement in constructors(no compilation error)
class Test
{
Test()
{
this(10);
//this(10)Constructors this keyword must be first statement in constructors(no compilation error)
System.out.println("0 arg");
}
Test(int a)
{
this(10,20);
System.out.println(a);
}
Test(int a,int b)
{
System.out.println(a+"--------"+b);
}
public static void main(String[] args)
{
Test t=new Test();
}
}
Output :
note:-
1. inside the constructors constructor calling must be the first statement of the contructor other wise the compiler will raise compilation error.
2. The above rule applicable only for constructors.