我有一个抽象类,它有一个方法,所有扩展类的类都使用它。该方法对于每个类都是相同的,所以我不想在这些类中一遍又一遍地编写它。问题是该方法使用在每个类中声明的 2 个变量。如果没有那些变量 int eh 抽象类,我就不能在抽象类中使用该方法。但是如果我这样做,它们将采用抽象类中指定的值,而不是扩展它的类。我怎样才能解决这个问题?
示例代码:
public abstract class Example {
public String property1 = ""
public String property2 = ""
public ArrayList<String> getPropertyies() {
ArrayList<String> propertyList = new ArrayList<>();
propertyList.add(property1);
propertyList.add(property2);
return property1;
}
}
public class ExampleExtension extends Example {
public String property1 = "this is the property";
public String property2 = "this is the second property";
}
最佳答案
您应该将字段的范围限制为 private
在抽象类中并声明一个用于填充值的构造函数:
public abstract class Example {
private final String property1;
private final String property2;
protected Example(String property1, String property2) {
this.property1 = property1;
this.property2 = property2;
}
//...
}
然后子类将通过调用
super
在它们的构造函数中初始化字段值。构造函数:public class ExampleExtension extends Example {
public ExampleExtension() {
super("value1", "value2");
// initialize private fields of ExampleExtension, if any
}
// ...
}
关于java - 覆盖抽象字段 Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32213607/