为什么不是抽象字段? [英] Why not abstract fields?
问题描述
为什么 Java 类不能像抽象方法那样有抽象字段?
Why can't Java classes have abstract fields like they can have abstract methods?
例如:我有两个扩展同一个抽象基类的类.这两个类每个都有一个相同的方法,除了其中的一个 String 常量(恰好是一条错误消息).如果字段可以是抽象的,我可以使这个常量抽象并将该方法拉到基类中.相反,我必须创建一个抽象方法,在这种情况下称为 getErrMsg()
,它返回字符串,在两个派生类中覆盖此方法,然后我可以拉出该方法(现在调用抽象方法).
For example: I have two classes that extend the same abstract base class. These two classes each have a method that is identical except for a String constant, which happens to be an error message, within them. If fields could be abstract, I could make this constant abstract and pull the method up into the base class. Instead, I have to create an abstract method, called getErrMsg()
in this case, that returns the String, override this method in the two derived classes, and then I can pull up the method (which now calls the abstract method).
为什么我不能从一开始就将该领域抽象化?Java 是否可以设计为允许这样做?
Why couldn't I just make the field abstract to begin with? Could Java have been designed to allow this?
推荐答案
您可以通过在抽象类中使用 final 字段来实现您所描述的,该字段在其构造函数中初始化(未经测试的代码):
You can do what you described by having a final field in your abstract class that is initialised in its constructor (untested code):
abstract class Base {
final String errMsg;
Base(String msg) {
errMsg = msg;
}
abstract String doSomething();
}
class Sub extends Base {
Sub() {
super("Sub message");
}
String doSomething() {
return errMsg + " from something";
}
}
如果您的子类忘记"通过超级构造函数初始化 final,编译器将给出警告一个错误,就像未实现抽象方法一样.
If your child class "forgets" to initialise the final through the super constructor the compiler will give a warning an error, just like when an abstract method is not implemented.
这篇关于为什么不是抽象字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!