Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

java

 
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Report post to moderator
i want details about constructor in java doesn't have return type?
 
Ranch Hand
Posts: 1140
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Report post to moderator
This post doesn't belong to this forum. Java in General (beginner) seems to be more appropriate

Now, coming to your question: I think you want to know why the constructors doesn't return anything.
Let me try to explain with an example. Look at the following code


When the constructor is called? It is called when the new MyClass() is executed, right?
Assume for a moment that the constructor can return a value.
So, what will happen if the constructor did return something, say an int. It is similar to assigning a int value to the variable a, which is of type MyClass. This will definitely be an error.
So, the constructor, if at all can return something, can return only
a) an object of MyClass or
b) an object of some subclass of MyClass.
Returning anything else will trigger an error.

Now, you won't return an object of some subclass of MyClass, because the person calling the new MyClass() is expecting an object of MyClass and not it's subclass (otherwise he could have called new SubClassOfMyClass() straightaway)

This leaves us to one possibility: the constructor can return only the object of MyClass. So, why allow the constructor to return something, which might lead to potential problems? Better make it mandatory for the constructor not to return anything. Makes sense, isn't it?
 
Ranch Hand
Posts: 15304
6
Mac OS X IntelliJ IDE Chrome
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Report post to moderator
Wow, did the university courses start up already? Aren't you guys on Christmas break?

Since this question was already asked, and I mean, pretty much this question, just by someone else, I think it best to just close this thread and have the discussion continued where it started.
 
Do you pee on your compost? Does this tiny ad?
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com
    Bookmark Topic Watch Topic
  • New Topic