Why constructors are not return type? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Why constructors are not return type?

12th Aug 2019, 1:05 PM
Vikash Kumar Sharma
Vikash Kumar Sharma - avatar
5 Answers
+ 9
• A constructor is a special method whose name is same as that of the class name and it is called when you use the 'new' operator. Consider the following example :              School sc = new School(); Where,              School ➝ name of the class.                 sc      ➝ Object reference variable which stores the address of the object in the stack memory.           School() ➝ Constructor of the class.               new     ➝ is a special keyword that allocates the memory to store the object whose type is specified by a constructor and then calls the constructor to initialize the object, which is stored in the heap (a region of memory for storing objects). When constructor ends, new return memory addresses to the object so that it can be accessed from anywhere in the application.
12th Aug 2019, 5:50 PM
Danijel Ivanović
Danijel Ivanović - avatar
+ 5
When we create the object then the constructor will be automatically called by the JVM. If you don't define any constructor, the compiler automatically creates a default constructor and assign default values for all your variables in the class. Constructor is used to initialize the state of an object whereas Method is used to expose the behaviour of an object.
12th Aug 2019, 5:44 PM
Danijel Ivanović
Danijel Ivanović - avatar
+ 4
Constructors are used to initalize the object variables theres no reason for it to return anything you should make its methods to do that. 😊👍
12th Aug 2019, 1:38 PM
D_Stark
D_Stark - avatar
+ 2
Constructors automatically return the object that was being initialized. You can not make constructors to return anything else. Because return type is always known, no return type headings should be given.
12th Aug 2019, 1:55 PM
Seb TheS
Seb TheS - avatar
+ 2
Seb TheS I read that it returns the object but then I have read that the constructors return type is void and it's the "new" keyword that returns the refrenece to the object so thought I keep to what know and say that it cant return anything because I guess if you give it a return type it would end up being treated as a normal method. bit of a grey area for me bout what's happening behind the scenes 😅 maby my friend can help Danijel Ivanović
12th Aug 2019, 2:05 PM
D_Stark
D_Stark - avatar