简体   繁体   English

列表/数组(java)中的不同类(所有扩展同一个类)

[英]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.

相关问题 创建所有类的对象,以扩展Java中的抽象类 - Create objects of all classes extending an abstract class in java 如果我使用反射来获取扩展公共类的类,该列表是否还将包含所有递归继承的类? - If i use reflections to get the classes extending a common class will the list contain all the recursively inherited classes too? 抽象类需要知道所有扩展类吗? - Abstract Class needs to know all Extending Classes? 为扩展抽象类的所有类创建PointCut - Creating PointCut for all classes extending an abstract class 关于从基类扩展的类的问题(Java) - Questions on classes extending from a base class (Java) Java:扩展一个类,而不是在太多的类中执行相同的逻辑。 优点和缺点? - Java: Extending a class instead of performing same logic in too many classes. Pros and Cons? Java generics - 遍历从相同父级扩展的未实例化类列表并调用父级方法 - Java generics - iterating through list of uninstantiated classes extending from same parent and call parent method 在Java中,列出了不同的类? - In Java, list of different classes? 如何在不同的List类中使用相同的内部类? - How to use same inner class in different List classes? 如何在Java中不同模块的相同类之间将参数传递给类? - How to pass a parameter to a class between different modules' same classes in java?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM