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.
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.
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 ]
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?
Post by:autobot
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