wood burning stoves
The moose likes Beginning Java and the fly likes The Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "The "this" keyword and the constructor." Watch "The "this" keyword and the constructor." New topic

The "this" keyword and the constructor.

ven jovovich
Ranch Hand

Joined: Sep 06, 2012
Posts: 33
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:
"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.

Jacob Morehouse

Joined: Feb 22, 2012
Posts: 17
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.

Darryl Burke

Joined: May 03, 2008
Posts: 5115

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.

luck, db
There are no new questions, but there may be new answers.
Campbell Ritchie

Joined: Oct 13, 2005
Posts: 46412
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.
I agree. Here's the link: http://aspose.com/file-tools
subject: The "this" keyword and the constructor.
It's not a secret anymore!