Reputation: 3
class Test{
int x;
Test(int x){
this.x = x;
}
}
When we say this.x = x
the constructor hasn't been completed yet, so no object is created so how does this
actually refer to an object that hasn't been created yet?
Upvotes: 0
Views: 326
Reputation: 24691
A constructor is really more of an initializer than anything. When you call a constructor:
Test t = new Test(3);
it's the new
keyword that actually allocates/creates the space in memory, and then calls the constructor to build the object within that memory, initializing fields and placing memory wherever it needs to be. That's all abstracted away behind the setting of fields, which is what we usually do in the constructor.
Upvotes: 3