2015-08-25 200 views
2

我有一個抽象類,它有一個方法用於擴展類的所有類。該方法對於每個類都是相同的,所以我不想在這些類中反覆寫入。問題是該方法使用在每個類中聲明的2個變量。如果抽象類中沒有這些變量,我就不能擁有這個方法。但是,如果我這樣做了,它們將採用抽象類中指定的值,而不是擴展它的類。我怎樣才能解決這個問題?覆蓋抽象字段Java

示例代碼:

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

什麼是Java抽象字段? –

+2

這是一個非常**錯誤的編碼模式。任何好的IDE都會告訴你'ExampleExtension.property1' *是隱藏*'Example.property1'。如果你討厭閱讀你的代碼的人,繼續保持它,包括。你自己。 – Andreas

+1

同樣的評論可以說得很好。請以一些尊重和誠信評論。 – shaydawg

回答

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

子類,然後會通過調用初始化它們的構造函數的字段值構造函數:

public class ExampleExtension extends Example { 

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

你不必重寫的變量。您可以在構造函數中設置你的屬性的初始值:

public class ExampleExtension extends Example { 

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

} 

一個更好的方法是使用一個帶參數的構造函數雖然,因爲米克助記符在其他答案建議。

1

IMO米克的解決方案是最務實的,但請注意,還必須使性抽象的選項,然後用子類polymorphicism要求子類重寫的屬性實現:

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

使不同(例如, 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 
}