2 Replies Latest reply: Dec 20, 2006 2:28 AM by 796440 RSS

    constructor returning value??

    807607
      Hi,
      I have known that constructor code, that we write, should not return any value.
      But i have tried a sample code, where i have written a constructor(only on the fact that it has same method name as that of the class) which returns a value.

      public int SampleMain() {
      return 1;
      }

      Also, i wrote my main method so that i create an object of this type.

      SampleMain sample = new SampleMain();

      I have also learnt by compiling and executing this piece of code, that any such constructor written to return a value behaves as yet another instance method.
      In C++, when i write a similar constructor and compile, it fails saying constructor syntax is wrong.
      Why doesn't java mention this idea as an error, or atleast a warning?
        • 1. Re: constructor returning value??
          800322
          Why doesn't java mention this idea as an error, or
          atleast a warning?
          Because it's nothing but an ill-named method, and not a c'tor. C'tors have no return type by definition because
          - it doesn't make sense to have one as a c'tor is an initializer
          - there's nothing that could accept the value.
          • 2. Re: constructor returning value??
            796440
            Hi,
            I have known that constructor code, that we write,
            should not return any value.
            Not "should not." Does not. Can not.


            But i have tried a sample code, where i have written
            a constructor(only on the fact that it has same
            method name as that of the class) which returns a
            value.
            No, you didn't.

            You wrote a method that has the same name as the class. It's not a constructor. If you declare a return type or void, it becomes just another method--albeit a poorly named one.


            Why doesn't java mention this idea as an error, or
            atleast a warning?
            It's not a Constructor, just a method. And yeah, it's kind of confusing that Java lets you do that. I wish it didn't allow methods to have the same name as the class.