英文:
How does Liskov's Substitution Principle work for classes like Object?
问题
简而言之,Liskov的替换原则指出,基类(超类)的实例应完全可以被其派生类的实例替代,而不引入任何“破坏性代码”,比如引发新错误、更改方法契约等。
这意味着java.lang.Object
应可以在任何地方被其子类的实例替代。然而,每个类都是Object的子类型。
举个例子,我可以实例化一个类,比如NetworkAdapter
,并将其作为一个Object传递,根据LSP,我应该能够将该Object
实例转换为一个随机的子类,比如Foo
?然而,NetworkAdapter
和Foo
是彼此完全不兼容的。
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
契约的情况包括不正确地实现equals
和hashCode
。
英文:
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
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论