覆盖抽象字段Java

sha*_*awg 2 java oop abstract-class encapsulation

我有一个抽象类,它有一个扩展类的所有类使用的方法.对于每个类,该方法都是相同的,因此我不想在这些类中反复编写它.问题是该方法使用在每个类中声明的2个变量.我没有抽象类中的方法,没有这些变量和抽象类.但是如果我这样做,它们会采用抽象类中指定的值,而不是扩展它的类.我怎样才能解决这个问题?

示例代码:

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";
}
Run Code Online (Sandbox Code Playgroud)

Mic*_*nic 8

您应该将字段的范围限制为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;
    }
    //...
}
Run Code Online (Sandbox Code Playgroud)

然后,子类将通过调用super构造函数初始化其构造函数中的字段值:

public class ExampleExtension extends Example {

    public ExampleExtension() {
        super("value1", "value2");
        // initialize private fields of ExampleExtension, if any
    }
    // ...
}
Run Code Online (Sandbox Code Playgroud)