Java – 在子类构造函数中编写抽象类的主体部分

huangapple go评论145阅读模式
英文:

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;
    }
}

huangapple
  • 本文由 发表于 2020年10月26日 21:05:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/64537722.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定