第19 条:要么设计继承并提供文档说明,要么禁止继承

要么设计继承并提供文档说明,要么禁止继承

该类的文档必须精确地描述覆盖每个方法所带来的影响

对于非私有方法包括构造器的文档说明上必须标注这个方法调用了哪些可以被覆盖的类,是什么顺序调用的,调用结果是怎么影响后续方法处理的。可以被覆盖的类是指非final的、公有的、受保护的方法,后台线程或者静态初始化器可能会调用可被覆盖的方法。
调用的方法的文档末尾会有调用描述信息,写着: “ Implementation Requirements ”(实现要求… …),它由Javadoc 标签@ implSpec 生成。这段话描述了该方法的内部工作情况。
下面的是AbstractCollection的remove方法。

    /**
     * {@inheritDoc}
     *
     * @implSpec
     * This implementation iterates over the collection looking for the
     * specified element.  If it finds the element, it removes the element
     * from the collection using the iterator's remove method.
     *
     * <p>Note that this implementation throws an
     * {@code UnsupportedOperationException} if the iterator returned by this
     * collection's iterator method does not implement the {@code remove}
     * method and this collection contains the specified object.
     *
     * @throws UnsupportedOperationException {@inheritDoc}
     * @throws ClassCastException            {@inheritDoc}
     * @throws NullPointerException          {@inheritDoc}
     */
    public boolean remove(Object o) {
        Iterator<E> it = iterator();
        if (o==null) {
            while (it.hasNext()) {
                if (it.next()==null) {
                    it.remove();
                    return true;
                }
            }
        } else {
            while (it.hasNext()) {
                if (o.equals(it.next())) {
                    it.remove();
                    return true;
                }
            }
        }
        return false;
    }

这个方法就是移除集合中的指定元素, @implSpec下面写了具体的实现。这个remove方法调用了可被覆盖的iterator()方法,如果子类没有没有覆盖iterator()方法,那么就会抛出UnsupportedOperationException异常,所以我们再看文档的时候就知道怎么去写该类的子类了。
从上可以看出,继承打破了封装性,要想继承要么提供文档说明,要么就禁止继承,禁止继承可以设计成final的,或者私有化构造器,提供静态工厂方法来实例化该类。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值