Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Constructors in Java with implicit return type

I know pretty well about all the things regarding Constructors in Java, which I pen down below so as to ensure :

It can be tedious to initialise all the variables in a class each time an instance is created.

It would be simpler to have all the setup done at the time the object is first created.

Because the requirement for initialisation is so common, Java allows objects to initialise themselves when they are created. This automatic initialisation is performed through the use of a constructor.

The constructor is automatically c/d immediately after the object is created, before the new operator completes. They don’t have a return type, not even void.

Reading Herbert Schildt The Complete Reference, I came across this paragraph.

The implicit return type of a class' constructor is the class type itself. It is the constructor's job to initialise the internal state of an object so that the code creating an instance will have a fully initialised, usable object immediately.

I see myself really confused with the term 'implicit return type' even when knowing well constructors have no return type, not even void.

Can someone?

like image 373
Farhan Shirgill Ansari Avatar asked Oct 21 '25 18:10

Farhan Shirgill Ansari


1 Answers

It's just a confusing piece of text, basically. There's no concept of a return type for a constructor, as you say - you can think of them as being a bit like a method with a return type of the same type, but:

  • Java (annoyingly) lets you declare that sort of method directly, and it's not a constructor:

    public class Test() {
        // This is a spectacularly unhelpful method name. 
        public Test Test() {
            return new Test();
        } 
    }
    
  • The behaviour isn't really the same, particularly when it comes to chained constructors, where all the constructors work on the same object.

  • You never return anything.

I would try to avoid thinking of constructors as methods - there are too many ways in which they're special.

like image 160
Jon Skeet Avatar answered Oct 24 '25 08:10

Jon Skeet