Generally, a constructor cannot have any return type and it cannot return any value. So, it is invalid to have a return statement which returns a value inside a constructor.
But, if we recall. a return statement can be written in two ways:
As the constructor cannot return any value so it is invalid to use a return statement with return expression inside a constructor. But, we can use a return statement without a return expression inside the constructor as it simply returns the control to the caller without executing the rest of the constructor’s code.
Example:
But, if we recall. a return statement can be written in two ways:
- return statement with expression
return <expression>;
- return statement without expression
return;
As the constructor cannot return any value so it is invalid to use a return statement with return expression inside a constructor. But, we can use a return statement without a return expression inside the constructor as it simply returns the control to the caller without executing the rest of the constructor’s code.
Example:
class Person{ public Person(int age){ if(age < 0) return; // return statement without expression /* Perform some logic here */ } }
Note: It is not a good practice to use a return statement inside a constructor as it results in difficult to test and bad coding standard. There is no specific use in using a return statement in a constructor, unless if there's any logic/validation is implemented for error scenarios as shown in the above example.