我想实现一个抽象Java类。每个子类都必须实现一种抽象方法,以确保在每个子类中单独执行部分代码。还有其他方法可以避免通过从主类的构造函数中调用抽象方法来避免出现“警告”吗?
public abstract class Listener {
protected Date checkTime = new Date();
protected TypeUpdate type = UNKNOW;
public Listener(){
super();
this.setTypeListener();
}
public void setTime(Date date) {
if (date != null) {
return;
}
this.checkTime = date;
}
/* Abstract methods */
public abstract void execute();
protected abstract void setTypeListener();
}
谢谢。------------------------------编辑----------
确定,在构造函数中调用抽象方法是错误的。因此,我该怎么做才能强制继承类以实现具体的构造函数实现(例如,以一种或另一种方式初始化成员?)
您可以执行类似操作
class Hello {
private String message;
Hello(String message) {
this.message = message;
}
}
public class Main {
public static void main(String args[]) {
// Hello hello=new Hello(); //Not possible
Hello hello = new Hello("Hello"); // Forced to specify the value for message
}
}
您到达基类构造函数,并从该构造函数返回时,在子类构造器中,将进行所有字段初始化,其余代码形成子构造器。
为了确保调用某些方法,您可以稍后再懒地调用该方法。或传递一个独立的对象,作为整个孩子的“一部分”。
public Child() {
super(createPart());
}
private static Part createPart() {
return new Part().withAnswer(42);
}
public Base(Part part) { ... }
也可能有一个案例
所以:
class Base {
public final void foo() {
foo();
}
protected void onFoo() {
throw new IllegalStateException("Missing onFoo implementation "
+ getClass().getName());
}
}