Today, while implementing some testclasses in c#, I stumpled on some questions regarding inheritance (and interfaces) in c#. Below I have some example code to illustrate my questions.
interface ILuftfahrzeug
{
void Starten();
}
class Flugzeug : ILuftfahrzeug
{
public void Starten()
{
Console.WriteLine("Das Flugzeug startet, "+Dings());
}
protected string Dings()
{
return "Flugzeug Dings";
}
}
class Motorflugzeug : Flugzeug, ILuftfahrzeug
{
public new void Starten()
{
Console.WriteLine("Das Motorflugzeug startet, "+Dings());
}
protected new string Dings()
{
return "Motorflugzeug Dings";
}
}
class InterfaceUndVererbung
{
static void Main(string[] args)
{
//Motorflugzeug flg = new Motorflugzeug(); // case1: returns "Das Motorflugzeug startet, Motorflugzeug Dings"
//Flugzeug flg = new Motorflugzeug(); // case2: returns "Das Flugzeug startet, Flugzeug Dings"
ILuftfahrzeug flg = new Motorflugzeug(); // case3: returns "Das Motorflugzeug startet, Motorflugzeug Dings"
// if Motorflugzeug implements ILuftfahrzeug explicitly,
// otherwise "Das Motorflugzeug startet, Motorflugzeug Dings"
flg.Starten();
Console.ReadLine();
}
}
These are my questions:
- Declaring and initializing with Flugzeug flg = new Motorflugzeug(); (case2) I expected that Motorflugzeug.Starten is called instead of Flugzeug.Starten (and I'm pretty sure that this is the behaviour Java shows). openbook.galileo says that in that case using c# the runtime-type is Flugzeug. Is there any reason for that? For me such inheritance behaviour makes no sense.
- Same with ILuftfahrzeug flg = new Motorflugzeug(); (case3) - here I could work around by letting Motorflugzeug implement ILuftfahrzeug explicitly (as it is in the example code). But for me this is redundant since Flugzeug already implements ILuftfahrzeug.
- Now I want to overwrite a protected methods Dings() that is called by Starten(). If I run the code as it is implemented in the example everthing works fine. But if Starten() is not implemented in Motorflugzeug, Dings() of the baseclass will be called instead of Motorflugzeug.Dings(). I was told that Java also shows this behaviour.
Is there any pattern to get around this? Otherwise I would have to overwrite every method (here: Starten()) that calls the method that I actually intend to overwrite (here: Dings()), even if it is exactly the same as in the base class.