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.
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();
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.
You showed up just in time for the waffles! And this tiny ad:
Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koop