简体   繁体   中英

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. I have an array FlightArray which I created as:

Flight 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. 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.

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 NonTransferFlight extends Flight { }

class Flight { }

You can easily add NonTransferFlight objects to your array, as following:

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

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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