Java interface extends Comparable

前端 未结 2 954
清歌不尽
清歌不尽 2020-12-06 05:07

I want to have an interface A parameterised by T A, and also want every class that implements it to also implement Comp

2条回答
  •  难免孤独
    2020-12-06 05:20

    If you use comparable you do not need to specify the possibility for subtypes in the compare function, it is by nature possible to pass in any subtype of an object X into a method that declared a parameter of class X. See the code below for more information.

    public interface Test extends Comparable {
    
    }
    
    class TestImpl implements Test {
        @Override
        public int compareTo(final Number other) {
            return other.intValue() - 128;
        }
    }
    
    class TestMain {
        public static void main(final String[] args) {
            TestImpl testImpl = new TestImpl();
            testImpl.compareTo(Integer.MIN_VALUE);
        }
    }
    

提交回复
热议问题