8 Jun 2018

Constructor with return Statement

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:
  1. return statement with expression
    return <expression>;
  2. return statement without expression
    return;
Here, a return statement with return expression returns the control to the caller by returning a value of the given expression and this type of return statement is valid only inside the methods where return type is mentioned other than void. Where as a return statement without return expression simply returns the control to the caller without returning any value.

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.





Popular Posts

Write to Us
Name
Email
Message