What are the negative aspects of Java class Stack inheriting from Vector?

前端 未结 6 852
太阳男子
太阳男子 2020-11-30 04:35

By extending class Vector, Java’s designers were able to create class Stack quickly. What are the negative aspects of this use of inheritance, particularly for class Stack?<

6条回答
  •  广开言路
    2020-11-30 04:59

    Having Stack subclass Vector exposes methods that are not appropriate for a stack, because a stack is not a vector (it violates the Liskov Substitution Principle).

    For example, a stack is a LIFO data structure yet using this implementation you can call the elementAt or get methods to retrieve an element at a specified index. Or you can use insertElementAt to subvert the stack contract.

    I think Joshua Bloch has gone on record as saying that having Stack subclass Vector was a mistake, but unfortunately I can't find the reference.

提交回复
热议问题