Previous | Home | Next |
this is a keyword in Java. Which can be used inside method or constructor of class. "this" is a reference variabe which stores the reference of the method calling object. Every class contains only one "this" keyword irrespective of number of objects. When we call a member method of a class through an object then the reference of the calling object is automatically passsed an argument to the method and this reference will be received by the "this" inside the class. Also the name of every class member variable will be prefixed by this and dot operator automatically this is called as implict use of "this" keyword.
Sometimes the name of local variables is same as of instance member variable the priority will be given to local variable. It means local variable will override instance member variable. This is called as instance variable hiding. To use member variable in this case we have to prefix "this" and the dot operator before member name. this is called as explicit use of "this" keyword.
this can be passed as an argument to another method.
In java it is illegal to declare two local variables with the same name inside the same or enclosing scopes. But we can have local variables (parameters of member methods) having same name as of instance member variable of class. When a local variable has the same name as an instance variable, the local variables hides the instance variable. But this keyword allows us to refer to instance variable even if local variables hides it.
Syntax of using this keyword
this.varName
varName is a name of an instance variable.
Another use of the this keyword is it allows one constructor to explicitly call another constructor in the same class.
Example :
class C { private int x; private int y; void setData(int x,int y) { this.x=x; //this.x is the class member & x is local variable this.y=y; } void display() { System.out.println(x+"\t"+y); } } class CTest { public static void main(String args[]) { C a1=new C(); C a2=new C(); a1.setData(10,20); a2.setData(5,7); a1.display(); a2.display(); } }
output :
10 20 5 7
Previous | Home | Next |