Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

The "this" keyword and the constructor.

 
ven jovovich
Ranch Hand
Posts: 33
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all,
A very basic doubt. I can't understand how we can use the "this" keyword inside a constructor. I thought that "this" refers to the currently executing object, then how can we use this in a constructor? I mean, a constructor constructs an object, so how can we use "this" before the object is constructed? Please look at the below code (from the java tutorials):


I understand that "this.x" and "this.y" refers to the instance variables, but this is what the tutorial says:
http://docs.oracle.com/javase/tutorial/java/javaOO/thiskey.html
"Within an instance method or a constructor, this is a reference to the current object — the object whose method or constructor is being called."
The object has not been created yet....
Please let me know what I am missing.

Regards,
ven
 
Jacob Morehouse
Greenhorn
Posts: 17
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi ven,


Great question! A constructor is not really in use until it is called to construct an object, in which case the "this" keyword would point to that object. For example you might make a method in a class that absorbs input from an XML file, but just because that XML data doesn't exist at compile time doesn't mean there is a problem. The constructer only "constructs" when an object is instantiated: myObject something = new MyObject();

Home that helps.

Jake
 
Darryl Burke
Bartender
Posts: 5126
11
Java Netbeans IDE Opera
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
ven jovovich wrote:The object has not been created yet....
Please let me know what I am missing.

Read all about Initialization of Classes and Interfaces in the JLS.
 
Campbell Ritchie
Sheriff
Pie
Posts: 48981
60
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The constructor doesn’t really construct the object. The new operator creates the object from the class, and as soon as the object is constructed, the constructor is called. If you look at the link Darrly quoted, you find out it is a lot more complicated than I shall tell you, but the constructor sets up initial values for all the fields (or at least it ought to). The fields exist by the time the constructor is called, but they probably don’t have “real” values yet, so the constructor gives them those “real” values.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic