• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Error while using this keyword

 
Nelson Sam
Ranch Hand
Posts: 30
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello all
I am just a beginner in Java.I was trying this small this keyword program but caught up with error.


What is wrong in this below code?
I know we can directly print string name,but I want to use this keyword and then print.

 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24212
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Nelson.

Welcome to JavaRanch!

Your constructor for class "tstr" assigns a value to the member variable "this.name":

this.name = name;

but your class doesn't actually declare any member variables. Declaring this one would look like this:



 
Nelson Sam
Ranch Hand
Posts: 30
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Ernest Friedman for such a quick response.
Now I understand that this keyword can be used to refer a class variable.

To make it clear I modified constructor to



Please correct me if I am wrong
Thanks
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24212
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That looks good. Note that since the name of the member variable ("name") and the name of the parameter ("str") are different, and there's no confusion, using "this" is actually optional. Your code is fine, but most people will just write "name = str;", without the "this" -- it means exactly the same thing. If you have a parameter or other local variable and a member variable with the same name, though, then "this" is required if you want to refer to the member variable.

 
Nelson Sam
Ranch Hand
Posts: 30
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ernest Friedman-Hill wrote:That looks good. Note that since the name of the member variable ("name") and the name of the parameter ("str") are different, and there's no confusion, using "this" is actually optional. Your code is fine, but most people will just write "name = str;", without the "this" -- it means exactly the same thing. If you have a parameter or other local variable and a member variable with the same name, though, then "this" is required if you want to refer to the member variable.



Thank you so much.
I have now clearly understood the use of this keyword.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic