如何实现其通用模板扩展了另一个接口的通用接口?

时间:2019-05-20 16:51:40

标签: java generics interface

请考虑以下情形:

public interface WinningBatches<X> {
    Collection<X> getBatches();
}

public interface SubBatches<Y, Z extends WinningBatches<Y>> {
    Collection<Z> getGoals(Collection<Y> var);

    void submitTask(Z var);
}

我想实现SubBatch的接口吗?

我进行如下操作:

public class TotalBatches implements SubBatches<String, String extends WinningBatches<(What to write here?)>> {
    // override the methods of SubBatches.
}

我不知道如何实现子批处理...

2 个答案:

答案 0 :(得分:0)

  1. 您可以将String extends WinningBatches<(What to write here?)>替换为WinningBatches<String>

    interface TotalBatches extends SubBatches<String, WinningBatches<String>> {
        // override the methods of SubBatches.
    }
    
  2. 或实施WinningBatches并使用

    class StringWinningBatches implements WinningBatches<String> {
        @Override
        public Collection<String> getBatches() {
            return null;
        }
    }
    
    interface TotalBatches extends SubBatches<String, StringWinningBatches> {
        // override the methods of SubBatches.
    }
    

答案 1 :(得分:0)

您需要在Z扩展名中指定SubBatches<Y, Z extends WinningBatches<Y>>的类型,或在TotalBatches中将其保留为通用类型。

此外,类型声明(例如<T extends U>)必须由新接口声明,而不是扩展接口。

这里有3个示例可以解决您的问题:

// 1. Without specifying Z
public interface TotalBatches<Z extends WinningBatches<String>> extends SubBatches<String, Z> { }

// 2. Specifying Z   
public interface TotalBatches extends SubBatches<String, WinningBatches<String>> { }

// 3. Using custom extension of WinningBatches   
public interface StringWinningBatches extends WinningBatches<String> { }
public interface TotalBatches extends SubBatches<String, StringWinningBatches> { }