我知道这个问题已经被问了一百万次,但我不太确定我有我需要的解决方案。这个问题很可能有“否”的答案,但我愿意接受这个问题的其他解决方案。
我正在实现我自己的 Exception 类,它是从另一个也实现了 Iterable 的类扩展而来的。
class TCBPackageException extends TCBRuntimeException implements Iterable<TCBRuntimeException> {
private List<TCBRuntimeException> exceptions = new LinkedList<>();
TCBPackageException(Throwable t) {
super(t);
}
class TCBPackageIterator extends Iterator<TCBRuntimeException> {
public boolean hasNext() {
...
}
public TCBRuntimeException next() {
...
}
}
public void addException(TCBRuntimeException e) {
exceptions.add(e);
}
// Here's My ISSUE
// When getMessage() is Called on TCBPackageException I want the accumulation of all the messages stored.
@Override
public String getMessage() {
StringBuffer buffer = new StringBuffer(super.getMessage());
for (TCBException ex : exceptions) {
buffer.append(ex.getMessage());
}
return buffer.toString();
}
// If I use an Iterator and end up getting this as the FIRST object, I just want the message of THIS exception.
public String getMessage() {
return super.getMessage();
}
最佳答案
来自https://docs.oracle.com/javase/tutorial/java/javaOO/methods.html
The Java programming language supports overloading methods, and Java can distinguish between methods with different method signatures. This means that methods within a class can have the same name if they have different parameter lists (there are some qualifications to this that will be discussed in the lesson titled "Interfaces and Inheritance").
考虑到这一点,你不能定义两个具有绝对相同签名的方法(像@Override这样的注释不属于签名)。如果您定义两个没有任何区别的方法 getMessage()
,编译器将不知道您试图通过 o.getMessage()
调用哪一个。
您必须以不同的方式命名它们或定义不同的参数集。建议:
@Override
public String getNestedMessages() {
StringBuffer buffer = new StringBuffer(super.getMessage());
for (TCBException ex : exceptions) {
buffer.append(ex.getMessage());
}
return buffer.toString();
}
第二个方法 getMessage()
绝对已经过时了,因为如果您不重写它,您会自动从父类(super class)中调用它。
关于java - 创建相同方法名称的 2 个实现;一个来自@Override,另一个来自派生的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51774294/