如何解释构造函数中的return语句?

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

并且

return ; 

在任何方法内部意味着返回void。

所以在我的程序中

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

我在打电话

 return; 

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

请解释 。

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

例如

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

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

人们可以争论这是否是一个好主意。 问题恕我直言,结果对象很难使用,因为它们没有任何你可以依赖的不变量。

在我到目前为止看到的所有在构造函数中使用return示例中,代码都存在问题。 通常构造函数太大并且包含太多的业务逻辑,因此很难进行测试。

我见过的另一种模式在构造函数中实现了控制器逻辑。 如果需要重定向,则构造函数存储重定向并返回调用。 除了这些构造函数也难以测试之外,主要问题是无论何时必须使用这样的对象,您都必须悲观地假设它没有完全初始化。

更好地保留构造函数中的所有逻辑,并以完全初始化的小对象为目标。 然后你很少(如果有的话)需要在构造函数中调用return

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

如果你在if条件ex的基础上在构造函数中进行一些初始化,你可能想要初始化数据库连接(如果它可用)并返回,否则你想要从本地磁盘读取数据用于临时目的。

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

使用void返回类型声明的方法以及构造函数只返回任何内容。 这就是你可以在其中省略return语句的原因。 为构造函数指定void返回类型的原因是为了区分构造函数和具有相同名称的方法:

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

在这种情况下, return行为类似于break 。 它结束初始化。 想象一下有int var类。 您传递int[] values并希望将var初始化为存储在values任何正int (否则为var = 0 )。 然后你可以使用return

 public class MyClass{ int var; public MyClass(int[] values){ for(int i : values){ if(i > 0){ var = i; return; } } } //other methods } 
 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