【问题标题】:Call another constructor from constructor after other instructions在其他指令之后从构造函数调用另一个构造函数
【发布时间】:2015-07-20 08:16:43
【问题描述】:

我有 2 个构造函数,接受不同类型的参数:

public Board(String s) {

    // the string is parsed to an int array.
    int[] array = doSomething(s);

    this(array);
}

public Board(int[] array) {
    doSomethingElse(s);
}

但是,在第一个构造函数中,我得到“构造函数调用必须是构造函数中的第一条语句”。有没有办法让构造函数在执行其他操作后调用另一个构造函数,还是仅仅是 Java 的限制?

【问题讨论】:

    标签: java constructor


    【解决方案1】:

    不,您不能在另一个构造函数中执行其他操作后调用构造函数。构造函数是Java中非常特殊的方法。但是您有两种选择:

    1。如果你在调用另一个构造函数之前要做的所有事情都是预处理参数,你可以这样写:

    public Board(String s) {
        this(doSomething(s));
    }
    
    private static int[] doSomething(String s) {...}
    

    您可以调用任何静态方法并将其结果传递给另一个构造函数。

    2。如果您的预处理意味着修改当前对象,因此您不能使用静态方法执行此操作,则可以调用特殊方法(如两个构造函数中的 init()):

    public Board(String s) {
        int[] array = doSomething(s);
    
        init(array);
    }
    
    public Board(int[] array) {
        init(array);
    }
    
    private void init(int[] array) {
        // do something else
    }
    

    【讨论】:

      【解决方案2】:

      作为Java的规则,应该首先调用this

      public Board(String s) {
          this(doSomething(s));
      }
      

      【讨论】:

      • @Ramesh-X 确实如此,如果 doSomething() 是静态的。
      【解决方案3】:

      它不必是构造函数。你可以这样做:

      public Board(String s) {
      
          // the string is parsed to an int array.
          int[] array = doSomething(s);
      
          this.sharedMethod(array);
      }
      
      public Board(int[] array) {
          this.sharedMethod(array);
      }
      
      public void sharedMethod() {
       //yourLogic
      }
      

      【讨论】:

        【解决方案4】:

        在 java 中是的,当您从另一个构造函数调用构造函数时,构造函数调用应该是第一条语句。看下面的代码 sn -p 和 cmets -

        public class Board{
        
           //no-argument consturctor
           public Board(){
                 //if the 'Board' class has a super class
                //then the super class constructor is called from here
               //and it will be the firs statement
               //the call can be explicit or implicit
        
              //Now do something
           } 
        
          public Board(int size){
             //call to no-arg constructor 
        
             this(); // explicit call to the no-argument constructor - 'Board()'
             //Now you can do something
             //but after doing something you can not 
             //make an explicit/implicit constructor call.
          }
        }
        

        【讨论】:

          猜你喜欢
          • 2011-03-24
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2010-12-15
          • 1970-01-01
          • 1970-01-01
          • 2014-03-12
          • 1970-01-01
          相关资源
          最近更新 更多