OneCompiler

Methods.this keyword

//1.this can be used to refer current class instance variable.
public class ThisKeyword{
String n;
ThisKeyword (String n)
{
this.n=n;
}
void display()
{
System.out.println("tutorial abt this keyword "+n);
}
public static void main(String[]args){
ThisKeyword t=new ThisKeyword("sun");
t.display();
}
}
//2.this can be used to invoke current class method (implicitly)
public class ThisKeyword{

void display()
{
this.display1();
System.out.println("tutorial abt this keyword ");
}
void display1()
{
System.out.println("hii ");
}
public static void main(String[]args){
ThisKeyword t=new ThisKeyword();
t.display();
}
}

//3.this() can be used to invoke current class contructor.
public class Thiskeyword{
Thiskeyword()
{
System.out.println("hii");
}
Thiskeyword(int x)
{
this();
System.out.println(x);
}
public static void main(String[] args) {
Thiskeyword t=new Thiskeyword(10);
}
}

//4.this can be passed as an argument in the method call.
public class ThisKeyword {
void m(ThisKeyword obj)
{
System.out.println("invoke");
}
void s()
{
m(this);
}
public static void main(String[] args) {
ThisKeyword t=new ThisKeyword();
t.s();
}
}
//5.this can be passed as an argument in the constuctor call.
class C
{
ThisKeyword ob;
C(ThisKeyword ob)
{
this.ob=ob;
}
void display()
{
System.out.println(ob.data);
}
}
public class ThisKeyword {
int data=100;
ThisKeyword()
{
C c=new C(this);
c.display();
}
public static void main(String[] args) {
ThisKeyword t=new ThisKeyword();
}
}
//6.this can be used to return the current class instance from the method.
class B
{
B getB()
{
return this;
}
void dis()
{
System.out.println("hello");
}
}
public class Thiskeyword{
public static void main(String[]args){
new B().getB().dis();
}
}