[英]Different classes (all extending the same class) in a list/array (java)
I want to make a list of instances of classes. 我想列出一个类的实例。 The instances belong to different classes, though they all belong to the same super class. 这些实例属于不同的类,尽管它们都属于同一个超类。 Is this something I should avoid? 这是我应该避免的事情吗? Or is this fine. 还是这样很好。 Any suggestions on how to best implement this, would be great. 关于如何最好地实现这一点的任何建议都将是很棒的。
For example, I have a super class Vehicle and two other classes, Bike and Car as classes that extend Vehicle. 例如,我有一个超级类Vehicle和另外两个类Bike和Car作为扩展Vehicle的类。 For convenience I want to store all Vehicles in one array/list as I want to display all vehicles using a simple loop. 为了方便起见,我想将所有车辆存储在一个阵列/列表中,因为我想使用一个简单的循环显示所有车辆。
Hope I am not seriously overlooking something and this doesn't turn out to be too trivial (or just bad practice). 希望我不会严重忽视某些东西,并且这不会太琐碎(或只是不好的做法)。
It surely is a legal move : 这肯定是合法的举动 :
public class Main {
public static void main(String[] args) {
List<Vehicle> list=new ArrayList<>();
list.add(new Car());
list.add(new Bike());
}
}
class Vehicle{}
class Car extends Vehicle{}
class Bike extends Vehicle{}
but it all depends on what you're trying to achieve. 但这完全取决于您要实现的目标。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.