据我所知,构造函数没有返回任何东西,甚至没有返回void,
和
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 ;
}
}
i am calling
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
(或var = 0
)中的任何正int
。然后你可以使用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