{
void method();
}
{
public void method()
{
Console.WriteLine("base implementation of method()");
}
}
Console.WriteLine("call base");
Base b = new Base();
b.method();
Console.WriteLine("call ibase");
IBase i = b;
i.method();
This yields:
So far so good. But what if you wanted to override the base method?
adding a new class throws a compiler error(class is below):
class Derived : Base
{
public void method()
{
Console.WriteLine("derived implementation of method()");
}
}
Error 1 Warning as Error: 'TipTester.Derived.method()' hides inherited member 'TipTester.Base.method()'. Use the new keyword if hiding was intended.
Solution is to add the new keyword to the derived method.
public new void method()
{
Console.WriteLine("derived implementation of method()");
}
Console.WriteLine("first implementation:");
Console.WriteLine("call derived");
Derived d = new Derived();
d.method();
Console.WriteLine("call base");
Base b = d;
b.method();
Console.WriteLine("call ibase");
IBase i = d;
i.method();
Yields the following:
Solution:
1. For the interface: make the derived class implement the interface directly (this is going to get clumsy fast). This solution also does not fix the base class problem.
2, Make the base class method virtual and the derived method override the base method. This implementation fixes all the inheritance issues. The new implementation of base and derived methods are the following:
public virtual void method()
{
Console.WriteLine("base implementation of method()");
}
public override void method()
{
Console.WriteLine("derivedbase implementation of method()");
}
{
Console.WriteLine("derivedbase implementation of method()");
}
3. Best implementation, however, would be to make the base method abstract and force the derived methods to implement it. This might not be optimal for those situations where you might not want to implement the abstract method every time.


No comments:
Post a Comment