Is it true that the constructor returns an object?

class Test{ public Test(){ System.out.println("I am here"); return;// not getting error } public static void main(String[] args){ Test test = new Test(); } } 

I am starting java. My teacher told me that the constructor returns an object and showed me the above example. this really happens because the method does not return any value, but return; doesn't get an error.

+5
source share
5 answers

No, the constructor initializes an object that has already been created. It does not return an object. Your mentor is wrong.

You do not need to write return; inside the constructor if you don't go back to the end of the code.

+7
source

No. The role of the constructor is to initialize the state of the object.

new keyword is responsible for creating the object on the heap. In the example below, using the new keyword, you create an object, and then point to this object of type Test name of the variable Test .

  Test test = new Test(); 
+2
source

No, that’s not at all true.

A constructor in Java is a block of code similar to a method that is called when an instance of an object is created. Here are the main differences between the constructor and the method:

  • The constructor does not have a return type.

  • The constructor name must be the same as the class name.

  • Unlike methods, constructors are not considered members of a class.

  • The constructor is called automatically when a new instance of the object is created.

Example:

 class Bike1{ Bike1(){ System.out.println("Bike is created"); } public static void main(String args[]){ Bike1 b=new Bike1(); } } 
+2
source

this line of code

 return; 

the dose does not mean the return value, but it just ends with the execution of the contractor, and since it is on the last line, therefore, it is not necessary

situation when you use return in the constructor

 class Test { private int a; public Test(int a) { System.out.println("I am here"); if(a>10) { System.out.println("I'm Executed but not the rest of code"); return; } System.out.println("I'm the last line of constructor"); } ... } 

return to constructor it as a return method to void

+2
source

A constructor in java is a special type of method that is used to initialize an object.

The Java constructor is invoked during the creation of the object. It builds values, that is, provides data for the object, so it is known as a constructor.

But he does not have a return type, I am afraid that your mentor is mistaken in this matter, repeat it with him.

 class Car{ Car() { System.out.println("Car is created"); } public static void main(String args[]) { Car c=new Car(); } } 
+1
source

Source: https://habr.com/ru/post/1270809/


All Articles