简体   繁体   English

Java-具有不同对象类型的列表

[英]Java - List with different object type

I have a Parent class. 我有家长班。 I made an array of 3 parent objects. 我做了3个父对象的数组。 I also have a child class. 我也有一个儿童班。 Is it possible that I can have 1 of those 3 array elements be a child object? 是否可以让这3个数组元素中的1个成为子对象?

private ParentClass[] a = new ParentClass[3]

ParentClass a[] = {
     new ParentClass("0"),
     new ParentClass("1"),
     new ChildClass("2")
};

This works fine. 这很好。 But I'm wondering, is this the correct way of doing it or is there any easier/cleaner way? 但是我想知道,这是正确的方法还是有更简单/更清洁的方法?

New to java btw from C. C语言的Java btw的新手。

Alternatively you can do the following, List.of comes with Java 9. The returned list is immutable, immutable objects are very nice in a lot cases. 或者,您可以执行以下操作:Java 9附带的List.of。返回的列表是不可变的,在很多情况下,不可变的对象非常好。 Also in Java, we do Interface instance = new ImplementationClass() , for example List<Class> = new ArrayList<>() , ArrayList implements List interface 同样在Java中,我们执行Interface instance = new ImplementationClass() ,例如List<Class> = new ArrayList<>() ,ArrayList实现List接口

List<ParentClass> list = List.of( new ParentClass("0"), new ParentClass("1"), new ChildClass("2") );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM