aspose file tools*
The moose likes Beginning Java and the fly likes Error while using this keyword Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Error while using this keyword" Watch "Error while using this keyword" New topic
Author

Error while using this keyword

Nelson Sam
Ranch Hand

Joined: Jun 12, 2010
Posts: 30
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

Joined: Jul 08, 2003
Posts: 24183
    
  34

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:




[Jess in Action][AskingGoodQuestions]
Nelson Sam
Ranch Hand

Joined: Jun 12, 2010
Posts: 30
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

Joined: Jul 08, 2003
Posts: 24183
    
  34

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

Joined: Jun 12, 2010
Posts: 30
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.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Error while using this keyword