简体   繁体   中英

Interface relation with abstract class C#

I read that Interface is implicitly pure abstract. So why the methods of the class that implements interface does not prefix with override keyword?

interface IA
{
    void Method();
}

class B : IA
{
   public void Method()       // why it is not "public override void Method()"
   {
       Console.Writeline("A derived");
   }
}

EDIT For those who want to know where i read it. Go to abstract classes v/s interface section of below page: http://www.codeproject.com/Articles/6118/All-about-abstract-classes

An interface is not a pure abstract class, it's just an interface.

An interface declares a contract with public methods and properties that anything that implements it must respect. It does not provide anything except signatures.

On the other hand, an abstract class provides a base implementation for some or all of its features. It can provide actual logic. Interfaces cannot.

Overriding is replacing the logic in a method by another logic. As interfaces never provide any logic (they can't), it would be pointless to use the keyword override .

Two other very important differences:

  • You can only derive from one class (abstract or not), but you can implement as many interfaces as you want.
  • You can have structs implementing interfaces, but you cannot make an abstract struct, as struct can't inherit from one another.

The best way to think of interfaces is to consider them with a can relationship to the class you mark them against, as opposed to a parent class which can be thought as a is a relationship.

In your example there is no need to mention the override keyword, as you are not overriding any implemented behaviour, you are simple saying that you class needs to fulfil its contract to supply a Method() implementation.

Although interfaces can be thought of like a purely abstract class, there is a distinct difference in that a class can be marked to implement several interfaces whereas it can only inherit from one parent class.

class B : IA, IB, IC

So, you can pass your instance of your class as any of these interface types depending on which contact you need to to expose to a method

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM