C# - Interface Clarification - c#

I read some points about interface:
"
Interface is the definition of contract that a class must conform.It does not
inherit anything.
"
while defining the differece between interface and abstract class can i say :
when a class is derived from abstract class it is known as real inheritance.When a class uses interface then it is not inheritance,it is an implementation of contracts ?

yes you are right . interface is just a contract to class.
note : Interfaces don’t derive from any System.Object-derived type. An interface is simply an
abstract type that consists of a set of virtual methods, each with its own name, parameters,
and return type. Interface methods can’t contain any implementation; hence, interface types
are incomplete(abstract).
e.g :
interface I1
{
}
interface I2
{
}
abstract class a1
{
}
abstract class a2
{
}
class App:a1,I1,I2 //no Error
{
static void Main(string[] args)
{
}
}
note : The CLR allows a type to inherit from only one other type, which has System.Object as its root base type
interface I1
{
}
interface I2
{
}
abstract class a1
{
}
abstract class a2
{
}
class App:a1,a2,I1,I2 // Error
{
static void Main(string[] args)
{
}
}

Yes ..you are right just to summarize
What is an Abstract Class?
An abstract class is a special kind of class that cannot be instantiated. So the question is why we need a class that cannot be instantiated? An abstract class is only to be sub-classed (inherited from). In other words, it only allows other classes to inherit from it but cannot be instantiated. The advantage is that it enforces certain hierarchies for all the subclasses. In simple words, it is a kind of contract that forces all the subclasses to carry on the same hierarchies or standards.
What is an Interface?
An interface is not a class. It is an entity that is defined by the word Interface. An interface has no implementation; it only has the signature or in other words, just the definition of the methods without the body. As one of the similarities to Abstract class, it is a contract that is used to define hierarchies for all subclasses or it defines specific set of methods and their arguments. The main difference between them is that a class can implement more than one interface but can only inherit from one abstract class. Since C# doesn't support multiple inheritance, interfaces are used to implement multiple inheritance.
Both Together
When we create an interface, we are basically creating a set of methods without any implementation that must be overridden by the implemented classes. The advantage is that it provides a way for a class to be a part of two classes: one from inheritance hierarchy and one from the interface.
When we create an abstract class, we are creating a base class that might have one or more completed methods but at least one or more methods are left uncompleted and declared abstract. If all the methods of an abstract class are uncompleted then it is same as an interface. The purpose of an abstract class is to provide a base class definition for how a set of derived classes will work and then allow the programmers to fill the implementation in the derived classes.

when a class is derived from abstract
class it is known as real
inheritance.When a class uses
interface then it is not
inheritance,it is an implementation of
contracts ?
Yes

The difference between an abstract class and an interface is that an interface does not define the implementation of any of this methods, and an abstract class provides some implementation. That's the only difference. The difference between an abstract class and a concrete class is that an abstract class has at least one member for which an implementation is not provided.
Interfaces can derive from other interfaces.
Multiple inheritance is only allowed for interfaces due to reasons which are complicated and part of the religious wars of a previous era.

When a class uses interface then it is
not inheritance,it is an
implementation of contracts
Yes, that is exactly how it is.
This may be a bit clearer if you look into what happens when you have one interface inheriting another one. That may be confusing since we just said that with interface it's not inheritance but just a contract definition. If you take the following code:
interface IA
{
void MethodA();
}
interface IB : IA
{
void MethodB();
}
class B : IB
{
public void MethodA() { }
public void MethodB() { }
}
class AB : IA, IB
{
public void MethodA() { }
public void MethodB() { }
}
If you examine the IL code of the classes B and AB (using ildasm or similar) you will find that both classes are identical when it comes to which interfaces they implement. The interface IB works as a "shortcut" to include also the interface IA, but there is no inheritance in the traditional sense involved.

The difference between an abstract class and an interface is best understood if you research the use of the two keywords in question:
C# abstract Keyword
C# interface Keyword
Essentially, an interface is a special construct that defines a code contract. It can contain no implementation whatsoever when you create it; it simply specifies the signatures of the properties and methods that the contract requires. When a class implements the interface, it must provide every property and method exactly as it is specified in the contract. It is the responsibility of the implementing class to provide the implementation.
An abstract class, however, is free to provide as much or as little implementation as it wants or needs to. It may, itself, implement an interface. All that is required of an abstract class is that it is marked abstract. Its members can be overriden by derived classes by marking the methods virtual in the abstract (base) class, and using the overrides keyword in the derived class. But the abstract base class is under no obligation to provide any functionality at all; nor is it under any obligation to provide a minimal number of virtual methods that lack implementation.
Hope this helps!

An interface is defining an interface. Just think of the word interface.
Simple.
It defines how you interact (interface!) with the class.
Just reroute your brain back around upon itself and you see the answer was right there in front of you.

Related

Can I override the properties and functions of a generically typed interface extending a non generic interface to consider generic type(s) in C#

What I have is a non generic interface for the purpose of having a common contact that I can call functions. The interface returns objects which implement other interfaces. For example:
public interface ISearchAdvancedInputController
{
ISearchAdvancedInput GetAdvancedInput();
void LoadFromModel(ISearchAdvancedInput advancedInput);
}
I then currently have an abstract generic class which implements the interface but imposes requirements of the type. The types of the abstract class must implement the same interfaces as the interface's properties and functions demand. I cast the generic type to the implemented type when necessary so that I can satisfy the requirements of the implemented non abstract interface. This way, I can extend this abstract class and it will enforce type requirements across a larger class w/ many different types used across it. For example:
public abstract class ISearchAdvancedInputControllerBase<standardInput, advancedInputType> : ISearchAdvancedInputController
where advancedInputType : ISearchAdvancedInput
{
protected abstract advancedInputType GetAdvancedInput();
ISearchAdvancedInput ISearchAdvancedInputController.GetAdvancedInput()
{
return GetAdvancedInput();
}
void ISearchAdvancedInputController.LoadFromModel(ISearchAdvancedInput advancedInput)
{
LoadFromModel((advancedInputType)advancedInput);
}
public abstract void LoadFromModel(advancedInputType advancedInput);
}
This works really well in general however it falls short because I'm having to use an abstract CLASS in order to perform this overriding. As such when I want to actually make use of it for more concrete examples, I encounter the error that I can only extend a single class.
So to get around this I extend the "other" class in the previous base abstract class. However this is not ideal because if I wind up creating another concrete implementation I need to redefine all of the type translations that I'm doing which is NOT related to the concrete classes implementation.
What I'd like is to not have an abstract class but instead some sort of abstract interface. If I had this I'd be able to implement concrete classes more succinctly. I've looked at other instances of this question and have tried what seems to be the main suggestion which is to make the initial interface generic and have the type extend the resulting interface type and then extend that interface with the more abstract interface as such:
interface TestGenericInterface<a> where a:TestClassInterfaceA
{
TestClassInterfaceA testGeneric { get; }
}
interface TestGenericComplexInterface<a> : TestGenericInterface<a>
where a:TestClassInterfaceA
{
new a testGeneric { get; }
}
However the concrete class seems to suffer from the same issue that's shown when you start from a non generic interface where each function / property of the base interface needs overwritten.
public class TestClass : TestGenericComplexInterface<TestGC>
{
public TestGC testGeneric => I want to complete this because its return is the type that I'm wanting to use for this concrete implementation
TestClassInterfaceA TestGenericInterface<TestGC>.testGeneric => I don't want to have to complete this because this function is already handled by the previous function in a round about sense.
}
public class TestGC : TestClassInterfaceA { }
I do see a note that I could provide default implementation of functions if I use c# v8.0 or greater, so I must be on a version prior to that but I figure this should be possible w/o that, but maybe in a different way. Hope ya'll can assist.

Why do abstract classes need to define abstract methods from interfaces they implement?

When an abstract class implements an interface, it is required to also either define or declare the methods (as asked before):
public interface MyInterface
{
void Method();
}
public abstract class MyAbstractClass : MyInterface
{
public abstract void Method(); // required, even though MyAbstractClass does not implement
}
public class MyClass : MyAbstractClass
{
public override void Method()
{
}
}
public interface MyInterface2 : MyInterface
{
// no need to declare Method() -- why can't abstract classes do the same for unimplemented methods?
}
What is the design rationale of the c# language to require the definition of abstract methods of abstract classes that implement interfaces? It seems completely redundant for an abstract class to be required to define a method that it does not implement (and to make it even worse, for the class that actually implements the method to have to mark the method as override). I see no reason why an abstract class could not behave like MyInterface2, which inherits from MyInterface but does not need to declare MyInterface's methods.
An abstract class is a fully-fledged type, just except it cannot be instantiated. Hence its full contract must be declared even though some of its methods are not implemented. A user of a particular abstract class must be able to bind to all its methods, be they coming from interfaces or directly declared in the abstract class. It the methods from interfaces were not (at least) declared (if not even implemented) in the abstract class, the used couldn't bind to them.
Further, classes and interfaces are somewhat loosely-coupled. A class may declare a method, which is later mapped to a same-signature method in an interface which is implemented by its descendant. Hence it is again a “good idea” from the language-design viewpoint to require all methods of interfaces being directly implemented on an abstract class to be actually declared in it.
You can think of an interface as a detachable feature (except when explicit implementations are used). The abstract class may live on its own and its direct users need not to know of any of its interfaces.
It's a design feature that only virtual methods can be left without an implementation, because the technical mechanism of virtual methods needs to be leveraged for the whole concept of abstract classes work in practice.
UPDATE: Example:
public interface IFoo { void M(); }
public abstract class Bar : IFoo
{
public virtual abstract void M();
public void N() { }
}
public class Baz : Bar
{
public override void M() { … }
}
…
public void Method(Bar par)
{
par.M();
}
…
Baz x = new Baz();
Method(x);
The Method see the instance denoted by the variable x as Bar — neither as Baz nor as IFoo. In other words, the user of class Bar does not care of whether it implemented one, two, ten, or no interface at all. All it does is access its members. It rely's on Bar's contract, not of IFoos contract. Hence if Bar implements IFoo, it must define all members from IFoo.
A method you create in an abstract class that implements the interface doesn't need to be abstract. Abstract classes can contain non-abstract methods too and you can define a full implementation of the interface there. The inheriting classes wouldn't need to override any of those methods.
Also, this is described in MSDN for abstract classes:
An abstract class must provide implementation for all interface members.
An abstract class that implements an interface might map the interface methods onto abstract methods.
Notice the word "might", it's not "has to".
Please also note what MSDN says about implementing an interface:
When a class or struct implements an interface, the class or struct must provide an implementation for all of the members that the interface defines.
This is true for all kinds of classes and structures.
A class which implements IFoo with method void Bar() has the option of whether or not it wishes to expose a public method Bar(), or whether it wishes to use a non-public member to implement the interface [C# requires the direct implementation method to be either public or private; vb.net also allows protected scope, which is often the most useful sort for abstract classes].
There are two useful ways via which an abstract class could implement IFoo.Bar():
public abtract void Bar();
// or
protected abstract void IFoo_Bar(); // Note that the exact name is arbitrary
void IFoo.Bar() { IFoo_Bar(); }
Both implementations are reasonable. The first would make an unjustified presumption that a class would want to have a public method which appears nowhere in its code; the latter would require the compiler to 'guess' at what name should be given to the abstract method. Because there is no behavior which would be clearly better than any alternative, C# requires the programmer to specify which behavior is desired.

Abstract Class and Interface in C#

I read an article from some site and in that article i read this :
Abstract classes can add more functionality without destroying the child classes that were using the old version. In an interface, creation of additional functions will have an effect on its child classes, due to the necessary implementation of interface methods to classes.
I don't understand what it means. Can anyone explain this more specifically , with a Good Example ?
this is the article which i read Link
Because interfaces only define members that types must implement, adding any new member to an interface will break any class that implements the old version because it inherently doesn't implement the new member. Any time you change the definition of an interface you must change every single class that implements that interface. Adding an abstract member to an abstract class does the same for derived classes but if you add a virtual member to the abstract class then it will have no impact on derived classes. They can be changed to override that member but they don't have to.
What it means is that if you consider a Abstract Class called Phone
and it has 3 virtual functions i.e.
AddPhonePrice , AddAccessoryPrice, AddAuxillaryPrice
and if there are two child classes
1) SamsungPhone 2) Iphone
now SamsungPhone will have implementation for all 3 functions.
while Iphone will have implementation for only AddPhonePrice, since they dont provide anything else with the phone
if we make interface called IMainPhone with
AddPhonePrice , AddAccessoryPrice, AddAuxillaryPrice functions
then both SamsungPhone and Iphone will need to implement all 3 functions
irrespective of whether they need them or not.
This means that you are able to add new members (methods, properties, fields, ...) to abstract classes that do not lead to changes in the derived classes - as long as the members are not abstract this is correct. For instance, consider this example:
internal abstract class MyBaseClass
{
public abstract void DoSomething();
// This method can also be added later without having an effect on the derived classes
public virtual void DoSomethingElse()
{
// Do something else...
}
}
internal class MyDerivedClass : MyBaseClass
{
public override void DoSomething()
{
// Do something...
}
}
In this case, the derived class has to implement the method DoSomething. But you can add non-abstract functions to the abstract base class later on. However, as soon as you add another abstract member to the base class, this also affects all non-abstract derived classes because the must implement the new members.
An interface on the other hand does not define concrete implementations at all but does only contain the abstract signature that all implementors must provide. Therefore, if you add a new member (method, property) to an interface it forces all implementors of the interface to also provide an implementation of the new members.
Interface: When you add a method to the base interface class, then you have to (manually) make sure all of the derived classes implement that method.
Abstract Base: When you add a method to an abstract base class, you aren't required by the compiler to implement that method in the derived classes.

What if you had an Abstract class with only abstract methods? How would that be different from an interface?

From my experience I think the following is true. If I am missing a major point please let me know.
Interface:
Every single Method declared in an Interface will have to be implemented in the subclass. Only Events, Delegates, Properties (C#) and Methods can exist in a Interface. A class can implement multiple Interfaces.
Abstract Class:
Only Abstract methods have to be implemented by the subclass. An Abstract class can have normal methods with implementations. Abstract class can also have class variables beside Events, Delegates, Properties and Methods. A class can only implement one abstract class only due non-existence of Multi-inheritance in C#.
So even that difference doesn't explain the question
1) What if you had an Abstract class with only abstract methods? How would that be different from an interface?
2) What if you had a Public variable inside the interface, how would that be different than in Abstract Class?
So any explanation will be vary help full.
Besides the technical differences it is mainly the intension of your design that should lead you to the decision to use one or the other:
Interfaces define the public API of the classes implementing them. Your goal of using an interface should be to show the usage of the classes that implement it. It is no side effect but a central design goal that a class can implement different interfaces to show the different roles it can act in.
An abstract class should implement some basic algorithm or common behaviour. It is mainly to join the common functionality of the subclasses in one place. Its purpose is to define the internal usage or flow and not the public interface. If you want to publish the usage of an abstract class it should implement a separate interface.
So:
1) An abstract class with only public abstract methods does not make any sense when you use the guidelines above. An abstract class can define protected abstract methods to define a flow or algorithm. But that is not possible with an interface.
2) Aditionally to the public properties abstract classes can define protected instance variables and therefor have many more usage scenarios (see explanation above).
EDIT: The "java" tag was removed by the author. I tried to make this as general as possible and it should be true for both java and C#
In Java:
An abstract class can implement an interface.
An interface cannot extend an abstract class.
BTW: Strangely - an abstract class can implement and interface without actually doing so.
interface I {
public String hello ();
}
interface J {
public String goodbye ();
}
abstract class A implements I, J {
#Override
abstract public String hello ();
}
class B extends A {
#Override
public String hello() {
return "Hello";
}
#Override
public String goodbye() {
return "goodbye";
}
}
All the variables of an Interface are by default public and static, you can not have a only public variable in an interface, whereas in an Abstract class you can declare a public variable.
If a class extends an Abstract class there is no any contract between them. Class which extends it may or may not override the abstract methods, however in case of interface there is a strict contract between the interface and the class that implements it, i.e the class will have to override all the method of that interface. So from the abstract method point of view they appears to be same, but are having completely different properties and advantages.
While your question indicates it's for "general OO", it really seems to be focusing on .NET use of these terms.
interfaces can have no state or implementation
a class that implements an interface must provide an implementation of all the methods of that interface
abstract classes may contain state (data members) and/or implementation (methods)
abstract classes can be inherited without implementing the abstract methods (though such a derived class is abstract itslef)
interfaces may be multiple-inherited, abstract classes may not (this is probably the key concrete reason for interfaces to exist separately from abtract classes - they permit an implementation of multiple inheritance that removes many of the problems of general MI).
As general OO terms, the differences are not necessarily well-defined. For example, there are C++ programmers who may hold similar rigid definitions (interfaces are a strict subset of abstract classes that cannot contain implementation), while some may say that an abstract class with some default implementations is still an interface or that a non-abstract class can still define an interface.
Indeed, there is a C++ idiom called the Non-Virtual Interface (NVI) where the public methods are non-virtual methods that 'thunk' to private virtual methods:
http://www.gotw.ca/publications/mill18.htm
http://en.wikibooks.org/wiki/More_C%2B%2B_Idioms/Non-Virtual_Interface
What if you had an Abstract class with only abstract methods? How
would that be different from an interface?
You can implement multiple interfaces but extend only one class
Abstract class are more immune to changes then interface becuase if you change an interface it would break the class implementing it.
Interface can have only static final fields..Abstract class can have any type of fields.
interface don't have constructor but abstract class can have it
But java docs say this
If an abstract class contains only abstract method declarations, it
should be declared as an interface instead.
Even if all the methods in today's version of an abstract class are abstract, future version of the class could add virtual or non-virtual methods without forcing modifications to implementations nor recompilation of consumers. By contrast, adding any member to an interface will generally require all classes which implement the interface be modified to implement that member, and both implementations and consumers will generally have to be recompiled regardless of whether the change added anything that wasn't already implemented.
The fact that abstract changes may be changed without breaking implementations or consumers is a big advantage in favor of abstract classes. On the other hand, an abstract class will force any implementing class to derive from it alone and no other class. By contrast, an interface will pose almost restrictions on what its implementers are allowed to inherit or derive from. That is a big advantage in favor of interfaces.
Because abstract classes and interfaces each have definite advantages, there are times when either may be better than the other. Conceptually, it would be possible to add a couple features to the way interfaces work that would give them the advantages presently enjoyed only by abstract classes, but I know of no particular plans to do so.
Your class can extends only one abstract class and implements many interfaces.
Well, in an abstract class you could also have fields, and auto-properties wouldn't need to be reimplemented. You can also specify access specifiers that aren't public. Also, it has better scalability (e.g. you can use [Obsolete] to mark an old implementation, and then make the new one call the old one by default). Also, it would stop you from having any more inheritance of classes. Another thing is that you can set static fields in abstract classes.
Also, interfaces are usually something that performs an action, while classes are about being that.
*1) What if you had an Abstract class with only abstract methods? How would that be different from an interface?*
By default the methods in an interface are 'public abstract' and the abstract class will also have the abstract methods as 'public abstract'.
If the abstract class contains only abstracts methods then it's better to make it an interface.
*2) What if you had a Public variable inside the interface, how would that be different than in Abstract Class?*
Interfaces can't have variables. If you meant properties, events, delegates etc... they would be by default 'Public'. If nothing is specified in the abstract class it would be 'Private'(In regards to members of the interface/abstract class only).
An interface is used when you want your class to be able to do something.
Your class extends an abstract class when there is a 'is a' relationship.
There is a semantic difference.
In case of abstract class.
class Dog : abstractAnimal
When we create object of Dog, we will have to create object of abstractAnimal to, it will lead to extra object creation.
In case of interface.
class Dog : IAnimal
When we create object of Dog, we will not be creating any extra object of anything.
In that case you can say:
1) We can specify different access modifier to methods present in class,
but we can't change access modifier of Interface member.
2) Derived class from abstract will not have a compulsion of
implementation.

Why do both the abstract class and interface exist in C#?

Why do both the abstract class and interface exist in C# if we can achieve the interface feature by making all the members in the class as abstract.
Is it because:
Interface exists to have multiple inheritance
It makes sense to have interface because object's CAN-DO feature should be placed in an interface rather base abstract class.
Please clarify
Well, an abstract class can specify some implemetation, but usually not all of it. (Having said which, it's perfectly possible to provide an abstract class with no abstract members, but plenty of virtual ones which with "no-op" implementations). An interface provides no implementation, merely a contract.
You could certainly argue that if multiple inheritance of classes were permitted, interfaces would be largely pointless.
Personally I don't get hung up on the whole "is-a" vs "can-do" distinction for inheritance. It never gives me as good an intuition about what to do as just playing around with different ideas and seeing which ones feel the most flexible. (Then again, I'm very much a "favour composition over inheritance" guy...)
EDIT: Just as the most convenient way of rebutting lbushkin's third point in his comment... you can override an abstract method with a non-virtual one (in terms of not being able to override it further) by sealing it:
public abstract class AbstractBase
{
public abstract void Foo();
}
public class Derived : AbstractBase
{
public sealed override void Foo() {}
}
Classes deriving from Derived cannot override Foo any further.
I'm not in any way suggesting I want multiple inheritance of implementation - but if we did have it (along with its complexity) then an abstract class which just contained abstract methods would accomplish almost everything that an interface does. (There's the matter of explicit interface implementation, but that's all I can think of at the moment.)
It's not a trivial question, it's a very good question and one I always ask any candidates I interview.
In a nutshell - an abstract base class defines a type hierarchy whereas an interface defines a contract.
You can see it as is a vs implements a.
i.e
Account could be an abstract base account because you could have a CheckingAccount, a SavingsAccount, etc all which derive from the abstract base class Account. Abstract base classes may also contain non abstract methods, properties and fields just like any normal class. However interfaces only contain abstract methods and properties that must be implemented.
c# let's you derive from one base class only - single inheritance just like java. However you can implement as many interfaces as you like - this is because an interface is just a contract which your class promises to implement.
So if I had a class SourceFile then my class could choose to implement ISourceControl which says 'I faithfully promise to implement the methods and properties that ISourceControl requires'
This is a big area and probably worthy of a better post than the one I've given however I'm short on time but I hope that helps!
They both exist because they are both very different things. Abstract classes permit implementation and interfaces do not. An interface is very handy as it allows me to to say something about the type I am building (it is serializable, it is edible, etc.) but it does not allow me to define any implementation for the members I define.
An abstract class is more powerful that an interface in the sense that it allows me to create an inheritance interface via abstract and virtual members but also provide some sort of default or base implementation if I so choose. As Spiderman knows, however, with that great power comes great responsibility as an abstract class is more architecturally brittle.
Side Note: Something interesting to note is that Vance Morrrison (of the CLR team) has speculated about adding default method implementations to interfaces in a future version of the CLR. This would greatly blur the distinction between an interface and an abstract class. See this video for details.
One important reason both mechanisms exist because c#.NET only allows single inheritance, not multiple inheritance like C++. The class inheritance allows you to inherit implementation from only one place; everything else must be accomplished by implementing interfaces.
For example, let's suppose I create a class, like Car and I subclass into three subclasses, RearWheelDrive, FrontWheelDrive, and AllWheelDrive. Now I decide that I need to cut my classes along a different "axis," like those with push-button starters and those without. I want all pushbutton start cars to have a "PushStartButton()" method and non-pushbutton cars to have a "TurnKey()" method and I want to be able to treat Car objects (with regard to starting them) irrespective of which subclass they are. I can define interfaces that my classes can implement, such as IPushButtonStart and IKeyedIgnition, so I have a common way to deal with my objects that differ in a way that is independent of the single base class from which each derives.
You gave a good answer already. I think your second answer is the real reason. If I wanted to make an object Compareable I shouldn't have to derive from a Comparable base class. if you think of all the interfaces think of all the permutations you'd beed to handle the basic interfaces like IComparable.
Interfaces let us define a contract around the publicly exposed behavior an object provides. Abstract classes let you define both behavior and implementation, which is a very different thing.
Interfaces exist to provide a class without any implementation whatsoever, so that .NET can provide support for safe and functional multiple inheritance in a managed environment.
An Interface defines a contract that an implementing class must fulfil; it is a way of stating that "this does that". An Abstract Class is a partial implementation of a class which is by definition incomplete, and which needs a derviation to be completed. They're very different things.
An abstract class can have an implementation while an interface just allows you to create a contract that implementers have to follow. With abstract classes you can provide a common behavior to their sub classes witch you can't with interfaces.
They serve two distinctly different purposes.
Abstract classes provide a way to have a an object inherit from a defined contract, as well as allowing behavior to be specified in the base class. This, from a theoretical standpoint, provides an IS-A relationship, in that the concrete class IS-A specific type of the base class.
Interfaces allow classes to define a (or more than one) contract which they will fulfill. They allow for a ACTS-AS or "can be used as an" type of relationship, as opposed to direct inheritance. This is why, typically, interfaces will use an adjective as they're name (IDisposable) instead of a noun.
An interface is used for what a class can do, but it is also used to hide some of things that a class can do.
For example the IEnumerable<T> interface describes that a class can iterate through it's members, but it's also limits the access to this single ability. A List<T> can also access the items by index, but when you access it through the IEnumerable<T> interface, you only know about it's ability to iterate the members.
If a method accepts the IEnumerable<T> interface as a parameter, that means that it's only interrested in the ability to iterate through the members. You can use several different classes with this ability (like a List<T> or an array T[]) without the need for one method for each class.
Not only can a method accept several different classes that implement an interface, you can create new classes that implement the interface and the method will happily accept those too.
The idea is simple - if your class(YourClass) is already deriving from a parent class(SomeParentClass) and at the same time you want your class(YourClass) to have a new behavior that is defined in some abstract class(SomeAbstractClass), you can't do that by simply deriving from that abstract class(SomeAbstractClass), C# doesn't allow multiple inheritance.
However if your new behavior was instead defined in an interface (IYourInterface), you could easily derive from the interface(IYourInterface) along with parent class(SomeParentClass).
Consider having a class Fruit that is derived by two children(Apple & Banana) as shown below:
class Fruit
{
public virtual string GetColor()
{
return string.Empty;
}
}
class Apple : Fruit
{
public override string GetColor()
{
return "Red";
}
}
class Banana : Fruit
{
public override string GetColor()
{
return "Yellow";
}
}
We have an existing interface ICloneable in C#. This interface has a single method as shown below, a class that implements this interface guarantees that it can be cloned:
public interface ICloneable
{
object Clone();
}
Now if I want to make my Apple class(not Banana class) clonable, I can simpley implement ICloneable like this:
class Apple : Fruit , ICloneable
{
public object Clone()
{
// add your code here
}
public override string GetColor()
{
return "Red";
}
}
Now considering your argument of pure abstract class, if C# had a pure abstract class say Clonable instead of interface IClonable like this:
abstract class Clonable
{
public abstract object Clone();
}
Could you now make your Apple class clonable by inheriting the abstract Clonable instead of IClonable? like this:
// Error: Class 'Apple' cannot have multiple base classes: 'Fruit' & 'Clonable'
class Apple : Fruit, Clonable
{
public object Clone()
{
// add your code here
}
public override string GetColor()
{
return "Red";
}
}
No, you can't, because a class cannot derive from multiple classes.

Categories

Resources