Java - 在 subclass 构造函数中写入抽象 class 的主体

Java - Writing the body of an abstract class in the subclass constructor

定义抽象 class 时,可以通过在对象定义处编写抽象方法的主体来创建该 class 的实例,如下所示:

AbstractClass obj = new AbstractClass() {   
   protected String description() {   return this.description;   }   
};

我也想做类似的事情,不过构造函数里面多了一个子class。像这样:

public class AbstractClass {
   String description;
   public AbstractClass(String description){
       this.description = description;
   }
   protected abstract String description();
}
public class ActualClass extends AbstractClass {
   public ActualClass(String description){
       super(description) {
       protected String description() {    return this.description;    }
       };
   }
}

现在,上面的代码不起作用。我怎样才能做类似的事情?

您不在构造函数中执行此操作,而是在 class 本身中执行:

public abstract class AbstractClass {
    String description;
    public AbstractClass(String description){
        this.description = description;
    }
    protected abstract String description();
}

public class ActualClass extends AbstractClass {
    public ActualClass(String description){
        super(description);
    }

    protected String description() {
        return this.description;
    }
}