how to explain return statement within constructor?

as far as i know , the constructor return nothing , not even void ,

and also

return ;

inside any method means to return void .

so in my program

public class returnTest {

    public static void main(String[] args) {
        returnTest obj = new returnTest();
        System.out.println("here1");

    }

    public returnTest () 
    {
        System.out.println("here2");
        return ;
    }
    }

i am calling

return;

which will be returning VOID , but constructor is not supposed to return anything , the program compiles just fine .

please explain .

Upvotes: 16

Views: 24926

Answers (6)

John3136
John3136

Reputation: 29265

return in a constructor just jumps out of the constructor at the specified point. You might use it if you don't need to fully initialize the class in some circumstances.

e.g.

// A real life example
class MyDate
{
    // Create a date structure from a day of the year (1..366)
    MyDate(int dayOfTheYear, int year)
    {
        if (dayOfTheYear < 1 || dayOfTheYear > 366)
        {
            mDateValid = false;
            return;
        }
        if (dayOfTheYear == 366 && !isLeapYear(year))
        {
            mDateValid = false;
            return;
        }
        // Continue converting dayOfTheYear to a dd/mm.
        // ...

Upvotes: 31

gaurav
gaurav

Reputation: 3

public class Demo{

 Demo(){
System.out.println("hello");
return;
 }

}
class Student{

public static void main(String args[]){

Demo d=new Demo();

}
}
//output will be -----------"hello"


public class Demo{

 Demo(){
return;
System.out.println("hello");

 }

}
class Student{

public static void main(String args[]){

Demo d=new Demo();

}
}
//it will throw Error

Upvotes: 0

Stepan
Stepan

Reputation: 1431

In this case return acts similarly to break. It ends initialization. Imagine class that has int var. You pass int[] values and want to initialize var to any positive int stored in values (or var = 0 otherwise). Then you can use return.

public class MyClass{

int var;

public MyClass(int[] values){
    for(int i : values){
        if(i > 0){
            var = i; 
            return;
        }
    }
}
//other methods
}

Upvotes: 1

AmitG
AmitG

Reputation: 10543

statements after return statement would be unreachable. If return statement is the last then it is of no use to define in constructor, but still compiler doesn't complain. It compiles fine.

If you are doing some initialization in constructor on the basis of if condition ex., you may want to initialize database connection if it is available and return else you want to read data from the local disk for temporary purpose.

public class CheckDataAvailability 
{
    Connection con =SomeDeligatorClass.getConnection();
    
    public CheckDataAvailability() //this is constructor
    {
        if(conn!=null)
        {
            //do some database connection stuff and retrieve values;
            return; // after this following code will not be executed.
        }

        FileReader fr;  // code further from here will not be executed if above 'if' condition is true, because there is return statement at the end of above 'if' block.
        
    }
}

Upvotes: 3

Philipp Cla&#223;en
Philipp Cla&#223;en

Reputation: 43979

return can be used to leave the constructor immediately. One use case seems to be to create half-initialized objects.

One can argue whether that is a good idea. The problem IMHO is that the resulting objects are difficult to work with as they don't have any invariants that you can rely on.

In all examples that I have seen so far that used return in a constructor, the code was problematic. Often the constructors were too big and contained too much business logic, making it difficult to test.

Another pattern that I have seen implemented controller logic in the constructor. If a redirect was necessary, the constructor stored the redirect and called returned. Beside that these constructors were also difficult to test, the major problem was that whenever to have to work with such an object, you have to pessimistically assume that it is not fully initialized.

Better keep all logic out of the constructors and aim for fully initialized, small objects. Then you rarely (if ever) will need to call return in a constructor.

Upvotes: 5

Mikhail Vladimirov
Mikhail Vladimirov

Reputation: 13890

Methods declared with void return type as well as constructors just return nothing. This is why you can omit return statement in them at all. The reason why void return type is not specified for constructors is to distinguish constructor from method with the same name:

public class A
{
    public A () // This is constructor
    {
    }

    public void A () // This is method
    {
    }
}

Upvotes: 1

Related Questions