对于非私有方法包括构造器的文档说明上必须标注这个方法调用了哪些可以被覆盖的类,是什么顺序调用的,调用结果是怎么影响后续方法处理的。可以被覆盖的类是指非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的,或者私有化构造器,提供静态工厂方法来实例化该类。