英文:
Java - Writing the body of an abstract class in the subclass constructor
问题
在定义抽象类时,可以通过在对象定义时编写抽象方法的方法体来创建该类的实例,就像这样:
AbstractClass obj = new AbstractClass() {
protected String description() { return this.description; }
};
我想做类似的事情,但是在子类的构造函数内部实现。就像这样:
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);
String desc = description();
}
protected String description() { return this.description; }
}
现在,上面的代码是无法工作的。我应该如何实现类似的功能呢?
英文:
When defining an abstract class, it is possible to create an instance of that class by writing the body of the abstract methods at object definition, like this:
AbstractClass obj = new AbstractClass() {
protected String description() { return this.description; }
};
I would like to do something similar, but inside the constructor of a sub-class. Something like this:
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; }
};
}
}
Now, the code above doesn't work. How could I do something similar?
答案1
得分: 3
你不在构造函数中进行此操作,而是在类本身中进行:
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;
}
}
英文:
You don't do it in constructor, but in the class itself:
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;
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论