如何在 Java 中处理组合/聚合和多态性
我有两个抽象类,我们称它们为 Car
和 Wheel
。我正在使用一些继承来处理不同类型的汽车。假设有两个派生 MonsterTruckCar
和 ToyCar
。此外,还有与 Car
相对应的不同类型的车轮,例如 TreadedWheel
和 PlasticWheel
(映射不一定需要从汽车类型到车轮类型都是一对一的)。另外汽车
由车轮
组成。
我认为在 Java 中能够做到这一点的方法是使用 Car
的属性作为 ArrayList
类型。我遇到的问题是,现在当我想在 Wheel
上使用多态性时,我不能,因为每当我处理 Wheel 时,它都是通过 ArrayList
而不是Wheel
的派生类。
我认为我也许可以使用有界通配符,或者只是使用大量 switch 语句来处理不同的组合,但我认为这些都不是最好的解决方案。我该如何处理这样的结构?
此外,如何将 Wheel
添加到 Car
中的组合/集合中。也就是说,我需要能够向 Car
添加可变数量的具体Wheel
,而且这将基于一些用户输入。所以我想在默认构造函数中有一个 while 循环,提示用户是否想要添加另一个轮子,然后如果他/她这样做,我会向聚合/收集的任何内容添加另一个 Wheel
他们在汽车
中。
编辑:将类本身的名称从复数 (Wheels
) 编辑为带有 's (Wheel
's) 的单数,以澄清关系。添加了最后一段,进一步解释了我正在寻找的行为。
I have two abstract classes, lets call them Car
's and Wheel
's. I am handling different types of cars using some inheritance. So lets say there are two derivations MonsterTruckCar
and ToyCar
. Additionally there are different types of wheels that correspond to the Car
s, say TreadedWheel
's and PlasticWheel
's (the mapping does not necessarily need to be one-to-one from types of cars to types of wheels). Further Car
's are composed of Wheel
's.
The way I thought I would be able to do this in Java is by using an attribute of Car
's to be type ArrayList<Wheel>
. The issue I am having is that now when I want to use polymorphism on the Wheel
's I cannot because whenever I deal with a Wheel it is through an ArrayList
which is not a derived class of Wheel
's.
I thought I might be able to use bounded wildcards, or just a lot of switch statements to handle different combinations but I dont think either of those would be the greatest solutions. How can I handle such a structure?
Further, how do you add Wheel
's to the composition/collection in Car
's. That is, I need to be able to add a variable amount of concrete Wheel
's to a Car
, further this is going to be based off of some user input. so I would like to have a while loop in the default constructor that prompt the user if he/she wants to add another wheel and then if he/she does I add another Wheel
to whatever is aggregating/collecting them in Car
's.
Edit: Edited the names of the classes themselves from plural (Wheels
) to singular with a 's (Wheel
's) to clarify the relationship. Added the last paragraph which explains further the behavior I am looking for.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
向指定车轮类型的 Car 类添加通用参数。这是一个非常基本的实现,您可以在此基础上构建:
编辑:
包括更新的要求,这很棘手,但可行......
Add a generic parameter to your Car class that specified the wheel type. Here's a very basic implementation you can build on:
Edited:
Includes updated requirements, which is tricky, but doable...