简体   繁体   English

在 Java 中使用 Inheritance 将子类 Object 添加到超类数组

[英]Adding An Subclass Object To An Made of Superclass Array With Inheritance In Java

So I have two classes which are Flight and NonTransferFlight, and Flight is superclass of the NonTransferFlight.所以我有两个类,分别是 Flight 和 NonTransferFlight,Flight 是 NonTransferFlight 的超类。 I have an array FlightArray which I created as:我有一个数组 FlightArray,我创建为:

Flight flightArray[] = new Flight[10];航班 flightArray[] = new Flight[10];

Problem is, when I want to add an NonTransferFlight object to this array, it doesn't allow me to do that.问题是,当我想将 NonTransferFlight object 添加到这个数组时,它不允许我这样做。 how can I do that?我怎样才能做到这一点?

Problem is, when I want to add an NonTransferFlight object to this array, it doesn't allow me to do that.问题是,当我想将 NonTransferFlight object 添加到这个数组时,它不允许我这样做。

I'm not very sure why you say that, because, in theory, you can do that.我不太确定你为什么这么说,因为从理论上讲,你可以这样做。

If you have the following class structure (as you described):如果您具有以下 class 结构(如您所述):

class NonTransferFlight extends Flight { }

class Flight { }

You can easily add NonTransferFlight objects to your array, as following:您可以轻松地将NonTransferFlight对象添加到数组中,如下所示:

Flight[] flightArray = new Flight[10];

flightArray[0] = new NonTransferFlight();
flightArray[1] = new Flight();
// ...

Not related, but as a general rule, please use Java-style array declaration: Flight[] flightArray , as opposed to what you have in the code, C-style array declaration: Flight flightArray[] .不相关,但作为一般规则,请使用 Java 风格的数组声明: Flight[] flightArray ,而不是您在代码中的 C 风格的数组声明: Flight flightArray[]

You can add it like this:您可以像这样添加它:

Flight flightArray[] = new Flight[10];
flightArray[0] = new NonTransferFlight();

or或者

Flight flightArray[] = new Flight[10];
NonTransferFlight ntf = new NonTransferFlight();
// Can set some props for ntf instance and then,
flightArray[0] = ntf;

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

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