haansi
haansi

Reputation: 5736

OOP, why object initialization is incorrect?

I have a little problem in coding in OO way.

Here is my code:

 public class BasicEngine
{
    public    string name = null;
    public  string id = null;

    public BasicEngine()
    {
        name = "Name of basic engine type";
        id = "Basic engine id here";
    }

}

public class SuperEngine: BasicEngine  
{
    public  string name = null;
    public  string address = null;

    public SuperEngine()
    {
        name = "Name of super engine here";
        address  = "Super engine  address here";
    }

}

I am making the objects of these classes in the following ways:

       BasicEngine e1 = new BasicEngine();
       MessageBox.Show("e1 type is " + e1.GetType().ToString());

       SuperEngine e2 = new SuperEngine();
       MessageBox.Show("e2 is " + e2.GetType().ToString());

       BasicEngine e3 = new SuperEngine();
       MessageBox.Show("e3 is " + e3.GetType().ToString());

       SuperEngine e4 =BasicEngine(); // error An explicit conversion exist (are you missing cast ?) and if I try to cast it like    SuperEngine e4 =(SuperEngine ) new BasicEngine(); it give run time error.

e1 is BasicEngine as it should be. e2 is SuperEngine as it should be.

Here are my confusion and questions:

  1. e3 is BasicEngine type and it shows its data, I expect it to be SuperEngine type, why it is ?

  2. e4 give error: error An explicit conversion exist (are you missing cast ?) and if I try to cast it like SuperEngine e4 =(SuperEngine ) new BasicEngine(); it give run time error.

Upvotes: 0

Views: 76

Answers (2)

Val Bakhtin
Val Bakhtin

Reputation: 1464

Q1: It is a SuperEngine, but e3.name is "Name of basic engine type", because name is

  1. a field
  2. and is not virtual (and fields can not be virtual)

but if you call ((SuperEngine)e3).name you will see "Name of super engine here".

Q2: To explain it with real world example: all trucks are cars, but not all cars are trucks. And if you pretend that any car is a truck - when you try to 'dump()' or to 'haul()' you will fail because not all cars initialized with truck gears.

Upvotes: 3

Jason
Jason

Reputation: 52523

Q1: This is because e3 is being declared as type BasicEngine. Because SuperEngine inherits from BasicEngine and e3 IS a BasicEngine, it's going to run the BasicEngine constructor.

Q2: Your syntax is just wrong. You need to do SuperEngine e4 = new BasicEngine();, but this will still throw an error. This is because the BasicEngine constructor doesn't know how to create a SuperEngine and therefore won't. Parent classes are unaware of their derived children, but derived children ARE aware of their parents.

Upvotes: 3

Related Questions