this keyword is a reference variable that refers to the current object.
Uses
It can be used to refer instance variable of current
class.
It can
be used to call current class constructor.
It can
be used to call current class method.
Example 1:
Using this keyword
class Add{
int a,b;
Add(int a,int b){
this.a=a;
this.b=b;
}
void display()
{
System.out.println("sum is:"+(a+b));
}
}
public class Result {
public static
void main(String[] args) {
Add a1=new
Add(67,78);
a1.display();
}
}
Output:
sum is: 145
Example 2:
Without using this keyword
class Add{
int a,b;
Add(int a,int b)
{
a=a;
b=b;
}
void display()
{
System.out.println("sum is:"+(a+b));
}
}
public class Result {
public static
void main(String[] args) {
Add a1=new
Add(67,78);
a1.display();
}
}
Output:
sum is:0
Example
3:
Where
this keyword is not required
class
Add{
int
a,b;
Add(int
c,int d){
a=c;
b=d;
}
void
display()
{
System.out.println("sum
is:"+(a+b));
}
}
public class
Result {
public static void main(String[] args) {
Add a1=new Add(67,78);
a1.display();
}
}
Output:
sum is: 145
No comments:
Post a Comment