从另一个调用一个构造函数,在 Java 中重载

Calling one constructor from another, overloaded in Java

我正在读这个 post:

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;

    //...
  }

  //...
}

有什么问题?

要委托给其他构造函数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.

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

class SomeClass {
  private RandomAccessFile RAF = null;

  public SomeClass(String theName) {
    this(new RandomAccessFile(theName, "r")); 
  }

  public SomeClass(RandomAccessFile RAFSrc) {
    RAF = RAFSrc;

    //...
  }

  //...
}