I have an argument with my friend. He told me that a constructor returns address of the object. And I disagree with him. So what do you think guys.. Special thanks for the answer which has 'reference'.
Constructor doesn't return anything. The call to new returns the reference to the newly created object(address or pointer to the object is not a Java term. In Java it's called reference. However, the idea is the same). Internally, the JVM calls the constructor of the object after it creates the object.
It's pretty trivial to demonstrate that a constructor cannot have a return statement in it, and so in this sense a constructor does not return anything. Is that what your friend is saying, though? He may mean something a little different.
The value of a class instance creation expression is a reference to the newly created object of the specified class.
Looked at from the outside, a constructor looks much like a special method that returns a reference to a newly created instance. Except for the additional keyword "new" in the calling syntax. That's not how they are defined in the JLS though.
Joined: Dec 11, 2012
I'm thankful to you guys for your kind reply: Stephan van Hulst, Jayesh A Lalwani, Seetharaman Venkatasamy, Paul Clapham, Mike Simmons.
Mike, my friend is saying "constructor does return the address of newly created object to the class instance". And I told him this is the job of 'new' keyword. But we both don't have any written proof to support our statement. Though here, you guys are favoring my statement. (I know "The value of a class instance creation expression is a reference to the newly created object of the specified class")
A constructor is a special block of code that is called by the JVM to initialize a newly created object. It's the job of the new operator to allocate memory, call the constructor to initialize the object in the allocated memory and then to return a reference to the object.
Note that a constructor is not a method, even though it superficially looks like a method.
You cannot call constructors directly. It doesn't really make sense to say that a constructor returns a reference to an object. Constructors simply don't return anything.
According to the list here: Java bytecode instruction listings, return is the command to "return void from method". That's what the constructor uses. There are other return commands used to return Objects or primitives (areturn, ireturn, lreturn, dreturn, freturn).
So in terms of what the constructor actually gets compiled into, it doesn't return anything.
Joined: Dec 11, 2012
Thanks! Jesper and Special Thanks! to you Matthew. Matthew, your info is more insightful. Now I close this post. I'm Thankful to all of you guys.