-5

I've created an abstract class called Vehicle and have 2 sub classes: Motorcycle and Automobile. How can I create an instance of Motorcycle by using type Vehicle? So something like this:

Vehicle m=new Motorcycle();

I am able to access all properties of the Vehicle class but it is not seeing the properties of the Motorcycle class. Thanks

jasmine
  • 361
  • 1
  • 3
  • 11
  • 1
    Well, either don't declare it as `Vehicle` but as `Motorcycle` or cast it to `Motorcycle` where you need to access properties or methods from this type. – Tim Schmelter Nov 25 '16 at 16:35

2 Answers2

2

When an instance of Motorcycle is seen as as Vehicle, then it, quite naturally, cannot give you access to Motorcycle's unique properties. That's the point of inheritance.

To access them, you have to type-cast the instance:

Vehicle v = new Motorcycle();
((Motorcycle)v).MotorbikeEngineVolume = 250;

When you cannot be sure the instance truly is a Motorcycle, use the is operator:

Vehile v = …
…
if (v is Motorcycle) 
{
    ((Motorcycle)v).MotorbikeEngineVolume = 250;
}
Ondrej Tucny
  • 27,626
  • 6
  • 70
  • 90
0

By writing above statement you will be able to access only those members of Motorcycle which are either inherited from Vehicle or overridden in Motorcycle but if you want to access those members of Motorcycle which are not part of Vehicle then you have to write: Motorcycle m=new Motorcycle(); By using this instance you will be able to access members of derived class . Thank You!