Java this keyword

‘this’

  • ‘this’ is a keyword that refers to¬†current class instance variable
  • current class constructor is referenced by ‘this’ keyword.
  • current class method (implicitly) is referenced by ‘this’ keyword.
  • If member variable and local variable name conflict than this can be used to refer member variable.
  • ‘this’ can be passed as argument in the constructor call.
  • ‘this’ keyword can also be used to return the current class instance.

Untitled

 

Write a program to show this keyword can be used to refer current class instance variable
class test
{
int rno;
String name;
test(int rno,String name)
{
this.rno = rno;
this.name = name;
}
void display()
{System.out.println(rno+” “+name);
}
public static void main(String args[])
{
test t1 = new test(1,”Adam”);
test t2 = new test(2,”Andrew”);
t1.display();
t2.display();
}
}

Output:
1 Adam
2 Andrew

Write a program to use this to refer the current class parameterized constructor as this()
class sample
{
private int x;
sample()
{
this(10);
this.access();
}
sample(int x)
{
this.x=x;
}
void access()
{
System.out.println(“x=”+x);
}
}
class test
{
public static void main(String args[])
{
sample s= new sample();
}
}

Output:
x=10

Leave a Reply

Your email address will not be published. Required fields are marked *