【发布时间】:2022-01-05 11:47:53
【问题描述】:
我们刚从大学 Java 中的异常开始,我在这个任务上坐了很长时间,但我仍然无法走得更远。
任务是根据构造函数中的参数自定义带有消息的异常。我的想法是为消息编写一个额外的方法,但我很难访问参数中的变量
这是我目前所拥有的
import java.util.Calendar;
public class BadUpdateTimeException extends Exception{
private final boolean b;
private final Calendar cal;
public BadUpdateTimeException(Calendar cal, boolean b) {
super(message());
this.b = b;
this.cal = cal;
}
private static String message() {
if(b == true) {
String s = "Update time is earlier than the last update: ";
return s;
}else {
String s = "Update time is in the future: ";
return s;
}
}
}
【问题讨论】:
-
static阻止您访问实例字段,请将其删除。但是在这种情况下,由于执行顺序,您应该将b作为参数传递给message。 -
但是如果我这样做了,我就无法在super中访问它了
-
但是如果我删除静态,super 中的消息将不再像我的编译器所说的那样工作。