[英]Assign subclasses to each array element (run-time type)
I have a base class Building
and subclasses House
and School
. 我有一个基础班, Building
和House
和School
子类。 I have declared an array
of Building
objects the following way. 我已经通过以下方式声明了一个Building
对象array
。 I am not sure how to assign subclasses to each array element (run time type). 我不确定如何为每个数组元素(运行时类型)分配子类。
Building[] House = new Building[3];
Building[] School = new School[2];
You can use instanceof
to determine the subclass 您可以使用instanceof
来确定子类
if (building instanceof House) {
House[0] = building;
}
I'm not sure if you are asking how to check types at runtime or to populate with types at runtime. 我不确定您是要问在运行时检查类型还是在运行时填充类型。 If the latter then see @Salah's answer using instanceof
. 如果是后者,则使用instanceof
查看@Salah的答案。 In particular, why the House
array is being populated with Building
objects while the School
array is being populated with School
objects is confusing me. 特别是,为什么House
阵列被填充Building
对象,而School
阵列被填充了School
的对象是混淆了我。
To assign: 分派:
Building[] house = new House[3];
Building[] school = new School[2];
You could also populate the array with Building
objects and then use type checking when you need to down the road. 您还可以使用Building
对象填充数组,然后在需要时使用类型检查。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.