Forums Register Login

constructors in java

+Pie Number of slices to send: Send
I know constructor is used to create an object and constructor is similar to a method and having the name as that of class but no return type.
SomeOne asked me why constructor doesn't has a return type.
+Pie Number of slices to send: Send
I suppose that when they designed the language they decided that constructors do not need a return type since the return type can only be the object that is being created.

In other words, if you had a constructor for a class called JavaRanch, it would always return an object of type JavaRanch. Since it can never return anything else, there would be no value in making the programmer specify the return type.

I guess.
+Pie Number of slices to send: Send
Moving to the Java In General (Intermediate) forum...
+Pie Number of slices to send: Send
Certainly Rick's on the right track: there's really no point in it having a return type. I don't think there's another reason any more profound than that this is how C++ did it, and Java copys C++'s superficial syntax.

Note that you, the programmer, can't actually call a constructor at all. You can only say "new JavaRanch(args)". In C++, which is similar, it's proper to say that the new operator itself calls the constructor here. In Java, new isn't the same sort of redefinable operator, and it doesn't have an implementation that calls the constructor. When you say "new JavaRanch()", the compiler generates bytecodes like



In other words, an uninitialized block of memory is created, and then the constructor (which is actually compiled into a void function named "<init>"!) is invoked to initialize it.
[ December 21, 2004: Message edited by: Ernest Friedman-Hill ]
+Pie Number of slices to send: Send
 

Originally posted by Ernest Friedman-Hill:
When you say "new JavaRanch()", the compiler generates bytecodes like



In other words, an uninitialized block of memory is created, and then the constructor (which is actually compiled into a void function named "<init>"!) is invoked to initialize it.

I'm not sure what that means. I know that Java gets compiled to bytecode, but how does examining the bytecode help to understand how constructors work? And what do "new #2", "dup", and "invokespecial #12;" mean?
These are the worst of times and these are the best of times. And this is the best tiny ad:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com


reply
reply
This thread has been viewed 851 times.
Similar Threads
Question re: Identifiers
retyrn type compulsory
Mock Question ...
return type of Constructor
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 28, 2024 13:13:35.