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:
-
e3 is BasicEngine type and it shows its data, I expect it to be SuperEngine type, why it is ?
-
e4 give error: error
An explicit conversion exist (are you missing cast ?)and if I try to cast it likeSuperEngine e4 =(SuperEngine ) new BasicEngine();it give run time error.
Q1: This is because
e3is being declared as typeBasicEngine. BecauseSuperEngineinherits fromBasicEngineande3IS aBasicEngine, it’s going to run theBasicEngineconstructor.Q2: Your syntax is just wrong. You need to do
SuperEngine e4 = new BasicEngine();, but this will still throw an error. This is because theBasicEngineconstructor doesn’t know how to create aSuperEngineand therefore won’t. Parent classes are unaware of their derived children, but derived children ARE aware of their parents.