简体   繁体   English

Java:在子类型中指定通用类型限制

[英]Java: Specifying generic type restrictions in a subtype

I have a question regarding generic types in Java. 我对Java中的泛型类型有疑问。 Specifically, at present, I have some code similar to this: 具体来说,目前,我有一些与此类似的代码:

public interface Foo {
   public <T> void bar(T[] list)
}

public class FooImpl implements Foo{
   @Override
   public <T extends Comparable<? super T>> void bar(T[] list) {
       ...
   }
}

The problem is, that the compiler now complaints, that I have not implemented the bar-method in my FooImpl class. 问题是,编译器现在抱怨,我还没有在FooImpl类中实现bar方法。

What I want is to put some extra restriction on the generic type, specifically that they should be comparable. 我想要对通用类型施加一些额外的限制,特别是它们应该具有可比性。 But I don't want to put that restriction in my Foo interface, as all implementations does not need that restriction. 但是我不想在Foo接口中添加该限制,因为所有实现都不需要该限制。 Is this possible, and what should I do to fix it? 这有可能吗,我应该怎么做才能解决?

Thanks a lot in advance! 在此先多谢!

EDIT 1: Fixed typos Class --> class and Interface --> interface. 编辑1:固定错别字类->类和接口->接口。 But the return types are still void, not T, which is irrelevant, I suppose. 但我认为返回类型仍然是无效的,而不是T,这是无关紧要的。 My actual return type is a boolean. 我的实际返回类型是布尔值。

EDIT 2: The actual code, as requested: 编辑2:根据要求的实际代码:

public interface SortedCriteria {

    public <E> boolean isSorted(E[] list);

}

public class AscendingCriteria implements SortedCriteria {

    @Override
    public <E extends Comparable<? super E>> boolean isSorted(E[] list) {
        int length = list.length;
        for (int i = 1; i < length; i++) {
            if (list[i].compareTo(list[i-1]) < 0) return false;
        }
        return true;
    }

}

What you want to do is rejected because it would completely break polymorphism. 您想要做的事情被拒绝了,因为它会完全破坏多态性。 A caller having a Foo instance could have an instance of your subclass or an instance of any other subclass. 具有Foo实例的调用者可以具有您的子类的实例或任何其他子类的实例。 And since the interface guarantees that the method can be called with any kind of array as argument, your subclass can't break this contract by limiting the kind of array it accepts (unless it does that at runtime, by checking the type of the array and by throwing an exception, of course). 并且由于该接口保证可以使用任何类型的数组作为参数来调用该方法,因此您的子类无法通过限制其接受的数组类型来打破此协定(除非它在运行时通过检查数组的类型来做到这一点)并引发异常)。

This boils down to the Liskov substitution principle, which is the basis of polymorphism and OO. 这归结为Liskov替换原理,它是多态性和OO的基础。

But maybe what you actually want is to make Foo a generic type: 但是也许您真正想要的是使Foo成为泛型类型:

public interface Foo<T> {
    public void bar(T[] list);
}

public class FooImpl<T extends Comparable<? super T>> implements Foo<T> {
   @Override
   public void bar(T[] list) {
       ...
   }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM