【问题标题】:how to explain return statement within constructor?如何解释构造函数中的返回语句?
【发布时间】:2013-02-18 04:30:56
【问题描述】:

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

还有

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 ,但构造函数不应该返回任何东西, 程序编译得很好。

请解释一下。

【问题讨论】:

  • 你听说过 java 命名约定吗?
  • 程序根本无法编译:它给出了一个无法访问的语句的编译错误。
  • @EJP :嘿,那是无意的,我刚刚写错了最后一行,它不应该在那里
  • "这将返回 VOID,但构造函数不应该返回任何东西......"。实际上,构造函数被编译成一个特殊的方法,叫做 ,它返回 void。

标签: java constructor return


【解决方案1】:

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

【讨论】:

    【解决方案2】:

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

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

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

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

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

    【讨论】:

      【解决方案3】:
      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.
              
          }
      }
      

      【讨论】:

        【解决方案4】:

        使用void 返回类型声明的方法以及构造函数什么都不返回。这就是为什么您可以在其中完全省略 return 语句的原因。之所以没有为构造函数指定void返回类型是为了区分构造函数和同名方法:

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

        【讨论】:

          【解决方案5】:

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

          【讨论】:

            【解决方案6】:
            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
            

            【讨论】:

            • 欢迎来到 StackOverflow!请不要只是在这里转储您的代码,请尝试为您的答案提供一个很好的描述。请花点时间阅读:stackoverflow.com/help/how-to-answer
            猜你喜欢
            • 2011-02-25
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2016-09-20
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多