Liskov替换原则如何适用于类似Object的类?

huangapple go评论69阅读模式
英文:

How does Liskov's Substitution Principle work for classes like Object?

问题

简而言之,Liskov的替换原则指出,基类(超类)的实例应完全可以被其派生类的实例替代,而不引入任何“破坏性代码”,比如引发新错误、更改方法契约等。

这意味着java.lang.Object应可以在任何地方被其子类的实例替代。然而,每个类都是Object的子类型。

举个例子,我可以实例化一个类,比如NetworkAdapter,并将其作为一个Object传递,根据LSP,我应该能够将该Object实例转换为一个随机的子类,比如Foo?然而,NetworkAdapterFoo是彼此完全不兼容的。

NetworkAdapter nA = new NetworkAdapter();
Object obj = (Object) nA;   // 完全正确和合法
Foo foo = (Foo) obj;   // ??? 这会引发ClassCastException!

我是否对LSP的理解有误?或者Java语言的结构在某些情况下违反了LSP?

英文:

In short, Liskov's Substitution Principle states that instances of the base (super) class should be completely replaceable with instances its derived (sub) classes without introducing any "breaking code" like throwing new errors, changing the contract of the methods, etc.

This means java.lang.Object should be replaceable with instances of any of its subclasses everywhere. However, every class is a subtype of Object.

I can instantiate a class say, for example, NetworkAdapter and pass it as an Object and according to LSP, I should be able to cast that Object instance into a random subclass, say Foo? However, NetworkAdapter and Foo are completely incompatible with each other.

NetworkAdapter nA = new NetworkAdapter();
Object obj = (Object) nA;   // completely okay and legal
Foo foo = (Foo) obj;   // ??? this would throw ClassCastException!

Am I understanding LSP wrong? Or does the structure of the Java language violate LSP in some cases?

答案1

得分: 1

如果您想以转型的方式思考LSP,它将涉及向上转型而不是向下转型。

您能否安全地将NetworkAdapter传递给接受Object的方法,或者子类是否违反了父类的契约?违反Object契约的情况包括不正确地实现equalshashCode

英文:

If you want to think about the LSP in terms of casting, it would be concerned with upcasting rather than downcasting.

Can you safely pass NetworkAdapter to a method that accepts Object or does the subclass violate the contract of the parent? Violations of the Object contract would include incorrectly implementing equals and hashCode.

huangapple
  • 本文由 发表于 2020年9月10日 13:00:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/63823095.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定