我正在阅读这篇文章:
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;
//...
}
//...
}
有什么问题?
最佳答案
委托(delegate)给其他构造函数 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
的情况。
关于java - 从另一个调用一个构造函数,在 Java 中重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36051377/