在 Java 中避免 RTTI
如果我有一个超类,例如动物,
和两个子类:斑马和长颈鹿,
如果我决定定义一个动物向量:
Vector <Animal> animals = new Vector();
并且我想说:你可以添加长颈鹿,但你必须先拥有至少一只斑马。
不使用 RTTI 的最佳方法是什么? (实例)
If I have a superclass, say Animal,
and two subclasses: Zebra and Giraffe,
If I decide to define a Vector of Animals:
Vector <Animal> animals = new Vector();
and I want to say: You can add Giraffes, but you must own at least one Zebra first.
What is the best way to do this without using RTTI? (instanceof)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
定义您自己的类:
另外两点:
就我个人而言,我会选择完全不使用继承的设计。因此,我的类将委托给它们,而不是子类化向量(或ArrayList):
Define your own class:
Two additional points:
Personally, I would go for a design that does not use inheritance at all. So instead of subclassing vector (or ArrayList) my class will delegate to them: