Can a class array contain subclass items?

I have one class named “Vessel”.
I have other 2 classes named “Ferry” & “Cargo” that extend the class “Vessel”.

I need to make a 4th class that has the attribute “schedule”, which is an array containing every ship. Each ship must be either of type “Ferry” or “Cargo”.

So is this correct?
Ferry schedule = new Ferry;

Could the above array contain objects of type “Ferry” and “Cargo” ?
If not, how can I accomplish this?

Example:

class Vessel {
    String name;
    int length;
    int year;
 
    Vessel(String n, int l, int y) {
        name = n;
        length = l;
        year = y;
    }
}
 
class Ferry extends Vessel {
    int passengerCount;
    int carCount;
}
 
class Cargo extends Vessel {
    int load;
}
 
class Port {
    String portName;
    Ferry schedule[] = new Ferry[];
}

Vessel schedule = new Vessel[2];

This line declares and instantiates an array of Vessels. (We don’t know what KIND of vessel each element in the array is… yet).

to add a ferry to element 0 of the array:

schedule[0] = new Ferry();

to add a cargo to element 1 of the array:

schedule[1] = new Cargo();

This is legal because both Cargo and Ferry ARE (derived from) Vessels.

Edit: Keep in mind the array variable, considers these to be Vessels, so elements in the array can only reference members of the Vessel class.

schedule[0].length = 23;  // is legal

but

schedule[0].passengercount=100;  // this is NOT legal

To get around this you CAN “cast” the array element to the appropriate vessel type:

((ferry)schedule[0])..passengercount=100;  // this IS legal, but ONLY if the schedule[0] was ACTUALLY instantiated (new) as a ferry.

If the array element was actually instated as a new cargo(), this command will generate a run-time
“type-mismatch” error. You can use GetType(), if you must, to check, but this is considered bad form.

Note: Unity serialization does NOT support inheritance. (this is only relevant if you want to SAVE the vessel array to disk). If it’s just a runtime array, don’t worry about this.