It could be a silly question, but I am learning, and I was just curious what's happening, today I was playing with few oops concepts and learning it in VS. I was again puzzled to see that we don't have to implement multiple interfaces same method into a derived class where ACTUALLY we "inherit" the interface, but in base class.
May I know how it works? My concern is, even though I do not "inherit" interface methods in base class, I use a method with same name. I also do not implement it in derived class.
Can somebody help me understand what's happening and how and why?
Class A
{
public void Display()
{
Console.Writeline("I am from A");
}
}
interface IA
{
void Display();
}
interface IB
{
void Display();
}
Class B : A, IA, IB
{
}
Class Final
{
static void Main()
{
B b = new B();
b.Display(); // displays class A Display method.
Console.Readline();
}
}
Although I can't speak for the language team, you can answer this question by posing the alternative solution.
You want to know why B
is considered to implement the interface IA
even though the required method definition is in base class A
, which doesn't implement the interface. So, let's consider the opposite: B
should not be considered to implement the interface because the base class' method wasn't written with that interface in mind.
This means that your code doesn't compile. Why doesn't it compile? Because B
doesn't implement required member Display
of interface IA
.
To fix this, you'd add a method Display
to class B
. That fixes the interface implementation. However, you now have a new compilation problem: you'll see a warning "B.Display()' hides inherited member 'ConsoleApplication1.A.Display()'. Use the new keyword if hiding was intended."
This is because your A.Display
wasn't overrideable - and you don't want to override it. You can implement a method to call base.Display()
if you choose, but this is extra code to essentially do nothing, and it makes a mess of your inheritance since a new
method is handled differently to an override. (If you write A x = new B(); x.Display();
then you'll actually call A.Display()
directly, which could get messy as your code evolves and is an accident waiting to happen.)
Alternatively, you might implement an entirely new B.Display
method. What you've also now done is hidden the method implemented in class A
from anyone who might derive from B
or create an instance of B
. Using new
to hide methods is rarely a recipe for an understandable object structure, and this would be no exception - all so that you can implement an interface cleanly.
So ultimately, I would imagine, this decision was made because the alternative is far too messy.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments