• Post Reply Bookmark Topic Watch Topic
  • New Topic

this keyword use  RSS feed

 
Rajesh Goud kumar
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
what is the use of this code? i have a little bit confusion on "this" keyword and what is the use of this code?

class Subscriber
{
int mdn;
String name;
Subscriber(int mdn,String name)
{
this.mdn=mdn;
this.name=name;
}
public String toString()
{
return ""+mdn+":"+name;
}
}
 
Abhijith Prabhakar
Ranch Hand
Posts: 56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
"this" refers to the current instance.
Subscriber(int mdn,String name)
{
this.mdn=mdn;
this.name=name;

}

In your code you have used same name for instance variable and method variable i.e. "mdn" and "name". This concept is also called as "Shadowing" as your method(local) variable is shadowing the instanc varibale.
So how do you assign a value to instance variable in method subscribe?
if you give "mdn = mdn" compiler will get confused to which mdn(local or instance) you are assigning a value. To remove ambiguity, you should use "this" saying to the compiler that left side attribute is instance variable and not local.

Hope this helps
 
Rajesh Goud kumar
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you sir.
 
Bakul Ghude
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
"This" keyword represt nothing but current object
that means if class and method contain same name of variable at that time if you want to use class variable or assign any value to class variable at that time programmer used this.variable_name ok
 
Dave Casman
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Abhijith Prabhakar:
"if you give "mdn = mdn" compiler will get confused to which mdn(local or instance) you are assigning a value.

Actually, the compiler doesn't get confused at all. It will use the local msn. It's the developer who expected the instance value to be set that usually gets confused.

 
Campbell Ritchie
Marshal
Posts: 55761
163
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Other uses of this:-
  • If you have more than one constructor (overloading) you can call them in turn saying this() or this(a, b, c). Must be first statement in constructor.
  • You can use this to mean the whole object. If you are serialising you can write writeObject(this).
  • If you are in an inner class you can't directly call the outer class object "this", but you can say OuterClass.this.
  •  
    • Post Reply Bookmark Topic Watch Topic
    • New Topic
    Boost this thread!