简体   繁体   English

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

[英]Calling one constructor from another, overloaded in Java

I was reading this post: 我正在读这篇文章:

How do I call one constructor from another in Java? 如何在Java中调用另一个构造函数?

call one constructor from another in java 在java中从另一个调用一个构造函数

But I don't know what is the problem whit my code: 但我不知道我的代码有什么问题:

NOTE : Only I'm using one call of constructor of three... the error message is indicated like message using // or /*...*/ ... 注意 :只有我正在使用一个三个构造函数的调用...错误消息表示为使用///*...*/消息...

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;

    //...
  }

  //...
}

What's the problem? 有什么问题?

To delegate to the other constructor this must be the first line in the constructor. 要委托给其他构造函数, this 必须是构造函数中的第一行。 I would suggest you re-throw IOException from the constructor. 我建议你从构造函数中重新抛出IOException Something like, 就像是,

class SomeClass {
    private RandomAccessFile raf = null;

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

    public SomeClass(RandomAccessFile raf) {
        this.raf = raf;
    }
}

Your other option is to duplicate the functionality (if you want to swallow the Exception) like, 你的另一个选择是复制功能(如果你想吞下Exception),比如

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

But then you need to deal with raf possibly being null . 但是你需要处理raf 可能null

When you call one constructor inside another one, it must be the first instruction. 当你在另一个内部调用一个构造函数时,它必须是第一个指令。

class SomeClass {
  private RandomAccessFile RAF = null;

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

  public SomeClass(RandomAccessFile RAFSrc) {
    RAF = RAFSrc;

    //...
  }

  //...
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM