I am currently in the process of learning Java, and I have done what I could to try and understand what these two things mean and do, but I simply don't get it. I have done a lot of googling, and also checked around for past questions on the site, but I still don't get it. So far I know that "this" somehow refers to some kind of method/variable/object, but I just don't get how it can refer to any of these, without (in the examples I have seen) actually specifing what to refer to, they just use the keyword "this.something or this(532);", it does not make sense. Same story with toString, they is no logic in these two that I get. Anyways, can anyone explain these two keywords in a simple way to me, and tell me how they can be even remotely useful in any program. Thanks in advance.
-
4What book or web tutorials are you using while learning Java? – pamphlet Apr 04 '13 at 17:47
-
1I don't think you are approaching this the right way. You need to learn the concepts and then the syntax. Do you know what an object is? Do you know the difference between a static and non-static instance of an object? What is a method? – ChaosPandion Apr 04 '13 at 17:53
-
`toString` is not a keyword, it is a method name. – user207421 Apr 05 '13 at 00:10
4 Answers
this.something
refers to object something
in the current class.
this.method()
refers to a method of the current class
this()
refers to constructor of the current class
toString()
is a method used to create String
representation of an object. Since every class in Java is a sub-class of Object
and Object
has toString()
method, every class has a default toString()
method. Often you will need to override the default toString()
in order to get meaningful results.

- 12,933
- 21
- 68
- 111
The this
keyword refers to the instance of the class.
this(512)
refers to a constructor of the class that takes an int as Argumentthis.field
refers to a field of the classthis.method()
refers to a method of the class
The toString()
method is inherited from Object but can be overridden in a subclass to get more meaningful output.

- 12,408
- 1
- 46
- 66
The this
keyword refers to the current instance of the class (see http://docs.oracle.com/javase/tutorial/java/javaOO/thiskey.html).
The toString()
keyword isn't a keyword: it is a method name. It is defined in the Object
class and can be overridden. What it does is creates the text representation of the class (see http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Object.html#toString()).

- 305,947
- 44
- 307
- 483

- 2,833
- 3
- 34
- 61
For example if your class is like the following: public class Database { public Database (int port){ } }
Then to refer this class' object, you can use like so: this(3306); As a result this keyword is used for referring to the class

- 1,448
- 4
- 24
- 42