覆盖抽象字段 Java

Overriding Abstract Fields Java

我有一个抽象 class,它有一个方法供所有 class 扩展 class 的方法使用。该方法对于每个 class 都是相同的,所以我不想在那些 class 中一遍又一遍地写它。问题是该方法使用了在每个 class 中声明的 2 个变量。如果没有这些变量 int eh abstract class,我就无法在 abstract class 中使用该方法。但如果我这样做,它们将采用抽象 class 中指定的值,而不是扩展它的 classes。我该如何解决这个问题?

示例代码:

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

您不必覆盖变量。您可以在构造函数中设置属性的初始值:

public class ExampleExtension extends Example {

    public ExampleExtension() {
        property1 = "this is the property";
        property2 = "this is the second property";
    }

}

更好的方法是使用带参数的构造函数,正如 Mick Mnemonic 在另一个答案中所建议的那样。

IMO Mick 的解决方案是最实用的,但请注意,您也可以选择将属性抽象化,然后使用子类多态性来要求子类覆盖 属性 实现:

public abstract class Example {
   public abstract String getProperty1();
   public abstract String getProperty2();

    public ArrayList<String> getPropertyies() {
        ArrayList<String> propertyList = new ArrayList<>();
        propertyList.add(getProperty1());
        propertyList.add(getProperty2());
        return propertyList;
    }
}

public class ExampleExtension extends Example {
    public String getProperty1() { return "this is the property"};
    public String getProperty2() { return "this is the second property"};
}

您应该在摘要 class 中将字段的范围限制为 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;
    }
    //...
}

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

public class ExampleExtension extends Example {

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

在这种情况下创建不同的(例如 property1、property2)抽象方法。搜索模板模式的相关阅读

public abstract class Example {
       public ArrayList<String> getPropertyies() {
        ArrayList<String> propertyList = new ArrayList<>();
        propertyList.add(getProperty1());
        propertyList.add(getProperty2());
        return property1;
    }

    public abstract getProperty1();//overriden by other class that has diff value for property1
    public abstract getProperty2();//overriden by other class that has diff value for property2
}