为什么要覆盖父接口中的现有方法?

时间:2020-07-10 18:34:12

标签: java

Spliterator OfPrimitive接口的定义如下:

public interface OfPrimitive<T, T_CONS, T_SPLITR extends Spliterator.OfPrimitive<T, T_CONS, T_SPLITR>>
            extends Spliterator<T> {
        @Override
        T_SPLITR trySplit();

        /**
         * If a remaining element exists, performs the given action on it,
         * returning {@code true}; else returns {@code false}.  If this
         * Spliterator is {@link #ORDERED} the action is performed on the
         * next element in encounter order.  Exceptions thrown by the
         * action are relayed to the caller.
         *
         * @param action The action
         * @return {@code false} if no remaining elements existed
         * upon entry to this method, else {@code true}.
         * @throws NullPointerException if the specified action is null
         */
        @SuppressWarnings("overloads")
        boolean tryAdvance(T_CONS action);
.....
}

在子界面中,我们有:

public interface OfInt extends OfPrimitive<Integer, IntConsumer, OfInt> {

        @Override
        OfInt trySplit();

        @Override
        boolean tryAdvance(IntConsumer action);
.....
}

为什么具有相同签名的tryAdvance在子界面中被覆盖?

我知道有一段时间可以在子接口中记录api规范或更改规范,我们可以覆盖父接口方法,但是在 tryAdvance 规范中没有任何更改,并且在子级之上没有文档界面,为什么要覆盖此方法?

1 个答案:

答案 0 :(得分:2)

这实际上不是相同签名。子接口带有类型参数,并重新定义了父方法的粗略签名。您没有义务这样做,但是我认为这是使API更具可读性和更清晰陈述的一种好方法。

鉴于孩子实现了某些方法,对我来说重要的是列出其他方法以强调这些方法实际上是要定义的。

一个更实际的理由是帮助记录事物。你不能说

{@link #tryAdvance(java.util.function.IntConsumer)}

除非有明确定义的方法

@Override
boolean tryAdvance(IntConsumer action);

请注意,在子级中定义的tryAdvance是指具体签名:

/**
 * {@inheritDoc}
 * @implSpec
 * If the action is an instance of {@code IntConsumer} then it is cast
 * to {@code IntConsumer} and passed to
 * {@link #tryAdvance(java.util.function.IntConsumer)}; otherwise
 * the action is adapted to an instance of {@code IntConsumer}, by
 * boxing the argument of {@code IntConsumer}, and then passed to
 * {@link #tryAdvance(java.util.function.IntConsumer)}.
 */
@Override
default boolean tryAdvance(Consumer<? super Integer> action) 
  
相关问题