繁体   English   中英

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

[英]Java - List with different object type

我有家长班。 我做了3个父对象的数组。 我也有一个儿童班。 是否可以让这3个数组元素中的1个成为子对象?

private ParentClass[] a = new ParentClass[3]

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

这很好。 但是我想知道,这是正确的方法还是有更简单/更清洁的方法?

C语言的Java btw的新手。

或者,您可以执行以下操作:Java 9附带的List.of。返回的列表是不可变的,在很多情况下,不可变的对象非常好。 同样在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