Liskov substitution principle - no overriding/virtual methods?

后端 未结 5 1363
旧巷少年郎
旧巷少年郎 2020-12-07 09:33

My understanding of the Liskov substitution principle is that some property of the base class that is true or some implemented behaviour of the base class, should be true fo

5条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-07 10:37

    No, it tells that you should be able to use derived class in the same way as its base. There're many ways you can override a method without breaking this. A simple example, GetHashCode() in C# is in base for ALL classes, and still ALL of them can be used as "object" to calculate the hash code. A classic example of breaking the rule, as far as I remember, is derivin Square from Rectangle, since Square can't have both Width and Height - because setting one would change another and thus it's no more conforms to Rectangle rules. You can, however, still have base Shape with .GetSize() since ALL shapes can do this - and thus any derived shape can be substituted and used as Shape.

提交回复
热议问题