2012-09-28 41 views
2

好了,所以我在一堆的信息,從一類叫做MonthlyReports有關客戶的文件中讀取。我也有一個名爲Customer的類,並且想要覆蓋其中名爲getTotalFees的方法,並且我有兩個名爲StandardCustomer和PreferredCustomer的子類,我希望getTotalFees被覆蓋。讀入的重要信息之一是客戶是首選還是標準(存儲在變量標誌中,但是我的問題是我不知道在哪裏/如何決定客戶是否是標準的還是首選。有條件重載方法在Java

這裏是我的主意,在客戶類我有抽象方法getTotalFees

public double abstract getTotalFees() { 
    return this.totalFees; 
} 

然後在我的標準和優選的類型我有一個重載的方法是

public double getTotalFees() { 
    if (flag.equals("S"){ 
     return this.totalFees * 5; 
    } else { 
     return this.totalFees; 
    } 
} 

我真的只是把握在這裏吸管,所以任何幫助將不勝感激。

回答

1

聽起來像是你需要一個工廠方法(又名「虛擬構造函數」)。讓多態性爲您解決這個問題。這是面向對象編程的標誌之一:

public class StandardCustomer extends Customer { 
    // There's more - you fill in the blanks 
    public double getTotalFees() { return 5.0*this.totalFees; } 
} 

public class PreferredCustomer extends Customer { 
    // There's more - you fill in the blanks 
    public double getTotalFees() { return this.totalFees; } 
} 

public class CustomerFactory { 
    public Customer create(String type) { 
     if ("preferred".equals(type.toLowerCase()) { 
      return new PreferredCustomer(); 
     } else { 
      return new StandardCustomer(); 
     } 
    } 
} 
+0

感謝這是更符合我所要求的 –

4

如果你已經有兩個不同的類StandardCustomerPreferredCustomer你可以有兩個不同版本的方法:

//in StandardCustomer: 
@Override 
public double getTotalFees() { 
    return this.totalFees * 5; 
} 

//in PreferredCustomer: 
@Override 
public double getTotalFees() { 
    return this.totalFees; 
} 
在Java中

動態調度需要照顧的正確方法是參與依賴於運行時類型的實例。