开发者

Class Implementing Two Interfaces which Define the Same Method

//inteface i11 
 public interface i11
    {
        void m11();
    }
//interface i22
    public interface i22
    {
         void m11();
    }

//class ab implements interfaces 开发者_Python百科i11 and i22
    public class ab : i11, i22
    {
        public void m11()
        {
            Console.WriteLine("class");
        }
    }

now when in Main() method we create an object of class ab which interface method will get called please explain all.


There's only one method implementation, so obviously that gets called, regardless of the type of the reference. I.E.:

i11 o = new ab();
o.m11();

and

i22 o = new ab();
o.m11();

are effectively the same.

ab.m11 satisfies the signature of the method in both interfaces. Also, you're not using explicit interface implementation, so that isn't a factor.


Interfaces merely say "Anything that implements this interface can be sure to have these methods".
If you think about it in that context, you'll see that it doesn't call the interface's method; rather, it merely implements the method calls required.


You are confusing the implementation of an interface with the extension of concrete class. I believe this is causing you to think of the relationship backwards. An interface, by definition, has no concrete implementation. It only defines a contract that implementing classes must use. Perhaps an example can help clarify.

Suppose we have an interface called IBank. This interface has the following definition:

IBank
{
    void AddMoney(int amount);
    void RemoveMoney(int amount);
    int GetBalance();
}

Then we have a concrete implementation of this interface as follows:

EuroBank : IBank
{
    void AddMoney(int amount){ balance+= amount; }
    void RemoveMoney(int amount){ balance-= amount; }
    int GetBalance(){ return balance; }
    private int balance;
}

I cannot create a new instance of IBank. The following code will not compile.

IBank bank = new IBank;

Instead, I must create a new concrete instance of a bank that I can treat as an IBank. I can then call methods on this class.

IBank bank = new EuroBank;
bank.AddMoney(7);

So when I call AddMoney, I using the method defined by the interface, but I am actually calling the concrete implementation of AddMoney on the EuroBank class.

So in your example, you are calling the m11 method on the ab class. However, ab implements both i11 and i22. Therefore, it can be treated as both an i11 and i22 object. Both of the following lines of code will work.

i11 first = new ab();
i22 second = new ab();

I can call the m11 method on either object, but it will always use the concrete implementation of the method found on the object ab.


The method is not an interface method.
The method that will be called is the m11 method of class ab.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜