So I know I can't actually access methods and attributes of a subclass from it's parent. But I have a program which stores Vehicles in an array (NOT arraylist - its homework). The Vehicles then initialize into either Airplane, Boat, or a Car object derived from the Vehicle class. These subclasses have attributes which are unique, and I'm wondering as to how I could go about accessing these?
Here's some (simplified) relevant code:
Vehicle[] vehicles = new Vehicle[20];
vehicles[0] = new Airplane();
// Setting an attribute of the superclass
vehicles[0].Make = "Boeing";
// Set an attribute from the Airplane class
vehicles[0].Engine = "Jet"; //(obviously this doesn't work)
How could I go about working around this? I've researched for a couple hours but I'm stumped by this one problem.
Thanks :)
You can access a reference through the type of its declaration. Because you declare the array to be of Vehicle
, you cannot directly access subclass members.
To do so, initialize the object separately from the collection that contains it:
var jet = new Airplane();
jet.Make = "Boeing";
jet.Engine = "Jet";
vehicles[0] = jet;
Alternatively, use an object initializer:
vehicles[0] = new Airplane
{
Make = "Boeing",
Engine = "Jet"
};
It would be quite nonsensical to cast it back just after instantiating it, but you could do that as well:
vehicles[0] = new Airplane();
((Airplane)vehicles[0]).Make = "Boeing";
((Airplane)vehicles[0]).Engine = "Jet";
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments