2013-03-04 52 views
7

据我所知,构造任何回报,甚至没有空隙,如何解释构造函数中的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,但构造函数不应该返回任何东西, 程序编译就好了。

请解释一下。

+6

你有没有听说过java的名称约定? – 2013-03-04 06:12:51

+1

该程序根本无法编译:它为无法访问的语句提供编译错误。 – EJP 2013-03-04 06:13:32

+1

@EJP:嘿,这是无意的,我错误地写了最后一行,它并不意味着在那里 – 2013-03-04 06:29:16

回答

15

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

例如

// A very contrived example... 
class Demo 
{ 
    protected int id = 0; 
    protected int count = 0; 
    public Demo(int id, int count) 
    { 
     this.id = id; 
     this.count = count; 
     if (this.count <= 0) { 
      return; 
     } 
     // count > 0, do something meaningful 
1

void返回类型声明的方法以及构造函数只是不返回任何内容。这就是为什么你可以省略return声明。为什么不构造指定void返回类型的原因是,从方法具有相同名称的区分构造:后声明

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

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

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

如果你正在做一些初始化的构造如果条件前的基础上,你可能需要初始化数据库连接(如果可用),并返回其他你想从本地磁盘临时读取数据目的。

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. 

    } 
} 
+2

否则在这一点上不会执行 – 2015-03-18 10:08:01

2

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

有人可能会说这是否是一个好主意。恕我直言,问题在于结果对象很难处理,因为它们没有任何可以依赖的不变量。

在我迄今所看到的所有例子,在一个构造函数中使用return,代码是有问题的。通常情况下,构造函数是太大,包含了太多的业务逻辑,因此很难进行测试。

,我已经在构造看出实现的控制器逻辑的另一种模式。如果一个重定向是必要的,构造存储重定向并叫回来。除此之外,这些构造函数也很难测试,主要问题是每当必须使用这样的对象时,必须悲观地认为它没有完全初始化。

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

1

在这种情况下,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 
}