java 如何解释构造函数中的返回语句?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15195578/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 18:47:21  来源:igfitidea点击:

how to explain return statement within constructor?

javaconstructorreturn

提问by Hussain Akhtar Wahid 'Ghouri'

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

据我所知,构造函数什么都不返回,甚至没有返回,

and also

并且

return ;

inside any method means to return void .

在任何方法中都意味着返回 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 .

这将返回 VOID,但构造函数不应返回任何内容,程序编译得很好。

please explain .

请解释 。

回答by John3136

returnin 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.

return在构造函数中只是在指定点跳出构造函数。如果在某些情况下不需要完全初始化类,则可以使用它。

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.
        // ...

回答by AmitG

statements after returnstatement 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 ifcondition 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.

return语句之后的语句将无法访问。如果 return 语句是最后一个,那么在构造函数中定义是没有用的,但编译器仍然不会抱怨。它编译得很好。

如果您根据if条件在构造函数中进行一些初始化,则您可能希望初始化数据库连接(如果可用)并返回其他您想从本地磁盘读取数据以用于临时目的。

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.

    }
}

回答by Philipp Cla?en

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

return可用于立即离开构造函数。一种用例似乎是创建半初始化的对象。

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 returnin a constructor, the code was problematic. Often the constructors were too big and contained too much business logic, making it difficult to test.

在我目前看到的所有return在构造函数中使用的示例中,代码都有问题。通常构造函数太大,包含太多业务逻辑,难以测试。

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 returnin a constructor.

最好将所有逻辑排除在构造函数之外,并以完全初始化的小对象为目标。那么你很少(如果有的话)需要调用return构造函数。

回答by Stepan

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

在这种情况下,其return作用类似于break。初始化结束。想象一下具有int var. 您通过int[] values并希望初始化varint存储在values(或var = 0以其他方式)中的任何正数。然后你可以使用return.

public class MyClass{

int var;

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

回答by Mikhail Vladimirov

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

void返回类型和构造函数声明的方法不返回任何内容。这就是为什么你可以完全省略return它们中的语句。void构造函数不指定返回类型的原因是为了区分构造函数和同名方法:

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

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

回答by gaurav

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