多态对象字符串 [英] Polymorphism Object String

查看:58
本文介绍了多态对象字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我没能理解多态性.

以这个例子:

Object o = new String ("foo");

我做不到

o.substring (1,2)

谁能给我解释一下这个问题?

can anyone explain this problem to me ?

推荐答案

这是 Liskov 的结果替换原则,其中指出(总结):

This is a consequence of the Liskov Substitution Principle, which states (summarized):

如果 S 和 T 是对象,并且 T 是 S 的子类型,那么可以在需要 S 的地方使用 T.

If S and T are objects, and T is a subtype of S, then T may be used where S is expected.

String is-a Object 的子类型,所以如果你的赋值操作需要 Object,那么它会愉快地接受 Object 或其任何子类型.

String is-a subtype of Object, so if your assignment operation expects Object, then it will happily accept Object or any of its subtypes.

(注意:Object 不是 String.所有的String都是Objectcode>s,但并非所有 Object 都是 Strings.)

(Note: Object is not a String. All Strings are Objects, but not all Objects are Strings.)

这并不意味着您可以访问任何子类型的方法.给定继承层次结构,Object 不知道其任何子项的特定方法,也不能 - 没有办法通知祖先类其后代的能力.因为 Object 没有与之关联的 substring 方法,所以您的代码正确地导致编译失败.

This doesn't mean you get access to any of the subtype's methods. Given the inheritance hierarchy, an Object has no clue about any of its children's specific methods, nor can it - there is no way to inform an ancestor class of its descendant's capabilities. Because Object has no substring method associated with it, your code correctly results in a compilation failure.

(而且它应该,因为 Object所有 类的祖先.不能保证任何给定的 ObjectString.)

(And it should, given that Object is the ancestor of all classes. There's no guarantee that any given Object is a String.)

长期建议是不要使用过度不具体的对象类型(随着您在层次结构链上的上升,功能变得不那么具体 - 当您上升到 Object) 来完成特定于更特定类型的事情.

The standing advice is to not use an overly inspecific object type (as you go up the hierarchy chain, the capabilities become less specific - you lose functionality as you go up to Object) to accomplish something specific to a more specific type.

这篇关于多态对象字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆