This keyword;

The this keyword refers to the current object in a method or constructor. The most common use of the this keyword is to eliminate the confusion between class attributes and parameters with the same name (because a class attribute is shadowed by a method or constructor parameter).

How we use this keyword?

This is a keyword in Java. Which can be used inside method or constructor of class. It(this) works as a reference to a current object whose method or constructor is being invoked. this keyword can be used to refer any member of current object from within an instance method or a constructor.

Program;

class Calculator{
int x=0;
int y=9;
public static void main(String args[]){
Calculator c=new Calculator();
c.x=7;
c.y=5;
c.add(2,3);
}
void add(int x,int y){
System.out.println(this.x+this.y);
System.out.println(x+y);
//this.sub(4,2);
}

void sub(int x,int y)

{

System.out.println(this.x-this.y);
System.out.println(x-y);

}
}

output;

12
14
2
7


Leave a comment

Design a site like this with WordPress.com
Get started