【问题标题】:Calling one constructor from another, overloaded in Java从另一个构造函数调用另一个构造函数,在 Java 中重载
【发布时间】:2016-07-03 06:13:51
【问题描述】:

我正在阅读这篇文章:

How do I call one constructor from another in Java?

call one constructor from another in java

但我不知道我的代码有什么问题:

注意:只有我使用三个构造函数的一个调用...错误消息表示为使用///*...*/ 的消息...

class SomeClass {
  private RandomAccessFile RAF = null;

  public SomeClass(String theName) {
    try {
      RandomAccessFile raf = new RandomAccessFile(theName, "r");
      this(raf); //call to this must be first statement in constructor
      SomeClass(raf); /*cannot find symbol
                        symbol:   method SomeClass(RandomAccessFile)
                        location: class SomeClass*/
      this.SomeClass(raf); /*cannot find symbol
                        symbol: method SomeClass(RandomAccessFile)*/
    } catch (IOException e) {}
  }

  public SomeClass(RandomAccessFile RAFSrc) {
    RAF = RAFSrc;

    //...
  }

  //...
}

有什么问题?

【问题讨论】:

    标签: java constructor nested constructor-overloading


    【解决方案1】:

    当你在另一个构造函数中调用一个构造函数时,它必须是第一条指令。

    class SomeClass {
      private RandomAccessFile RAF = null;
    
      public SomeClass(String theName) {
        this(new RandomAccessFile(theName, "r")); 
      }
    
      public SomeClass(RandomAccessFile RAFSrc) {
        RAF = RAFSrc;
    
        //...
      }
    
      //...
    }
    

    【讨论】:

      【解决方案2】:

      要委托给其他构造函数this 必须是构造函数的第一行。我建议你从构造函数中重新抛出IOException。类似的,

      class SomeClass {
          private RandomAccessFile raf = null;
      
          public SomeClass(String theName) throws IOException {
              this(new RandomAccessFile(theName, "r"));
          }
      
          public SomeClass(RandomAccessFile raf) {
              this.raf = raf;
          }
      }
      

      您的另一个选择是复制功能(如果您想吞下异常),例如,

      public SomeClass(String theName) {
          try {
              this.raf = new RandomAccessFile(theName, "r");
          } catch (FileNotFoundException e) {
              e.printStackTrace();
          }
      }
      

      但是你需要处理raf 可能null

      【讨论】:

        猜你喜欢
        • 2015-07-02
        • 2011-03-24
        • 2010-09-22
        • 1970-01-01
        • 1970-01-01
        • 2011-01-23
        • 2014-03-12
        相关资源
        最近更新 更多