2016-09-26 152 views
2

我想在android中實現基本的抽象類。Java泛型 - 抽象類抽象函數覆蓋

我的基本抽象類是BaseItemPresenter類。類別如下:

public abstract class BaseItemPresenter<T extends MvpView> extends BasePresenter<T> { 

    public abstract void loadFromDevice(); 

    public abstract void loadFromFile(); 

    public abstract void backup(List<? extends BaseBackupItem> list); 

    public abstract void delete(List<? extends BaseBackupItem> list); 

    public abstract void restore(List<? extends BaseBackupItem> list); 

    public abstract void sort(int sortType, boolean isAscending); 

    public abstract void sort(List<? extends BaseBackupItem> list, int sortType, boolean isAscending); 

    public abstract void filter(List<? extends BaseBackupItem> list, Class<? extends MvpView> filterOptions); 
} 

我正在用ItemPresenter1類實現這個類。代碼如下:

public class ItemPresenter1 extends BaseItemPresenter<MvpView> { 

    @Override 
    public void loadFromDevice() { 

    } 

    @Override 
    public void loadFromFile() { 

    } 

    @Override 
    public void backup(List<Item1> list) { 

    } 

    @Override 
    public void delete(List<Item1> list) { 

    } 

    @Override 
    public void restore(List<Item1> list) { 

    } 

    @Override 
    public void sort(int sortType, boolean isAscending) { 

    } 

    @Override 
    public void sort(List<Item1> list, int sortType, boolean isAscending) { 

    } 

    @Override 
    public void filter(List<Item1> list, Class<View1> filterOptions) { 

    } 
} 

Item1類擴展了BaseBackupItem類。 View1類正在擴展MvpView類。

public class Item1 extends BaseBackupItem { 

} 

public class View1 extends MvpView { 

} 

所以,我應該怎麼實現這個問題:

來自:

public abstract void backup(List<? extends BaseBackupItem>); 

到:

@Override 
public void backup(List<Item1>); 

錯誤:

Method does not override method from its superclass. 
+2

將另一個通用參數添加到類中,並使用IT作爲列表的類型 –

+0

爲什麼需要更改簽名?它的工作原理是 – Blackbelt

回答

1

你需要一個新類型參數爲了增加的BaseItemPresenter類定義指定List作爲未來預期的類型:

public abstract class BaseItemPresenter<T extends MvpView, I extends BaseBackupItem> 
    extends BasePresenter<T> { 
    ... 
    public abstract void backup(List<I> list); 

    public abstract void delete(List<I> list); 

    public abstract void restore(List<I> list); 

    ... 
} 

然後你ItemPresenter1類將被宣佈爲下一:

public class ItemPresenter1 extends BaseItemPresenter<MvpView, Item1 > { 
    ... 
    @Override 
    public void backup(List<Item1> list) { 
+0

。謝謝你的回答。 – okarakose