• Post Reply Bookmark Topic Watch Topic
  • New Topic

constructors in java  RSS feed

 
vara prasad
Ranch Hand
Posts: 47
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Rick Portugal
Ranch Hand
Posts: 243
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Gregg Bolinger
Ranch Hand
Posts: 15304
6
Chrome IntelliJ IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Moving to the Java In General (Intermediate) forum...
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
Rick Portugal
Ranch Hand
Posts: 243
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!