Abstract Class and Interface in C# - 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.

Related

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.

Abstraction Vs. Interface Confusion

Wait, before you start thinking, I would like to clear that I am NOT going to ask the routine differences between Interface and Abstract.
I had gone through the difference between Abstract and Interface in MSDN.
It is said :
By updating the base class, all inheriting classes are automatically updated with the change.
Interfaces, on the other hand, cannot be changed once created. If a new version of
an interface is required, you must create a whole new interface.
See this : -
Can anyone prove this using following example: -
abstract class WashingMachine
{
abstract public void Wash();
}
class Philips : WashingMachine
{
public Philips() { }
override public void Wash(){//Wash code here....}
}
class Samsung : WashingMachine
{
public Samsung() { }
override public void Wash(){//Wash code here....}
}
class Videocon : WashingMachine
{
public Videocon() { }
override public void Wash(){//Wash code here....}
}
Now, If I added following new abstract method in WashingMachine : -
abstract public void Rinse(int loadSize);
How all inheriting classes (i.e. Philips/Samsung/Videocon) will automatically get updated with the change?
They won't get updated - you still have to manually add an implementation of Rinse to each and every class that inherits from WashingMachine.
What I believe the MSDN says is that if you have a non-abstract method defined in an abstract class and you change that method, all classes that inherit from the abstract class will benefit from the change automatically.
Your concrete derived types all need to provide an implementation of any inherited abstract member...thus your types will still need to provide a Rinse implementation when you modified the base.
http://msdn.microsoft.com/en-us/library/sf985hc5(v=vs.71).aspx
This is a confusion programmers normally get when read difference between interface and abstract class. the line you refer is only true if the change in the abstract class is concrete. what i mean is you added a property or a method with implementation. Or if i am more specific, any change in base abstract class which does not make any concrete class abstract. Such change is possible in abstract classes and there is no way you can add such change in interface.
How all inheriting classes (i.e. Philips/Samsung/Videocon) will automatically get updated with the change?
They will suddenly become non-compileable, isn't that an update?
But I'd like to point out that there's in fact no difference between abstract method in abstract class and method in interface. Main difference lies in the fact that abstract classes can have methods with implementation and interfaces can not.
In fact, I'd say that I don't like MSDN definition and find it confusing and somewhat misleading.

Why does C# allow for an abstract class with no abstract members?

The C# spec, section 10.1.1.1, states:
An abstract class is permitted (but
not required) to contain abstract
members.
This allows me to create classes like this:
public abstract class A
{
public void Main()
{
// it's full of logic!
}
}
Or even better:
public abstract class A
{
public virtual void Main() { }
}
public abstract class B : A
{
public override sealed void Main()
{
// it's full of logic!
}
}
This is really a concrete class; it's only abstract in so far as one can't instantiate it. For example, if I wanted to execute the logic in B.Main() I would have to first get an instance of B, which is impossible.
If inheritors don't actually have to provide implementation, then why call it abstract?
Put another way, why does C# allow an abstract class with only concrete members?
I should mention that I am already familiar with the intended functionality of abstract types and members.
Perhaps a good example is a common base class that provides shared properties and perhaps other members for derived classes, but does not represent a concrete object. For example:
public abstract class Pet
{
public string Name{get;set;}
}
public class Dog : Pet
{
public void Bark(){ ... }
}
All pets have names, but a pet itself is an abstract concept. An instance of a pet must be a dog or some other kind of animal.
The difference here is that instead of providing a method that should be overridden by implementors, the base class declares that all pets are composed of at least a Name property.
The idea is to force the implementor to derive from the class as it is intended to provide only a basis for a presumably more specialized implementation. So the base class, while not having any abstract members may only contain core methods an properties that can be used as a basis for extension.
For example:
public abstract class FourLeggedAnimal
{
public void Walk()
{
// most 4 legged animals walk the same (silly example, but it works)
}
public void Chew()
{
}
}
public class Dog : FourLeggedAnimal
{
public void Bark()
{
}
}
public class Cat : FourLeggedAnimal
{
public void Purr()
{
}
}
I think a slightly more accurate representation of your question would be: Why does C# allow an abstract class with only concrete members?
The answer: There's no good reason not to. Perhaps someone out there has some organizational structure where they like to have a noninstantiatable class at the top, even if a class below it just inherits and adds nothing. There's no good reason not to support that.
You said it -- because you can't instantiate it; it is meant to be a template only.
It is not "really a concrete class" if you declare it as abstract. That is available to you as a design choice.
That design choice may have to do with creating entities that are (at risk of mixing the terminology) abstractions of real-world objects, and with readability. You may want to declare parameters of type Car, but don't want objects to be declarable as Car -- you want every object of type Car to be instantiated as a Truck, Sedan, Coupe, or Roadster. The fact that Car doesn't require inheritors to add implementation does not detract from its value as an abstract version of its inheritors that cannot itself be instantiated.
Abstract means providing an abstraction of behaviour. For example Vehicle is an abstract form. It doesn't have any real world instance, but we can say that Vehicle has accelerating behaviour. More specifically Ford Ikon is a vehicle, and Yamaha FZ is a vehicle. Both these have accelerating behaviour.
If you now make this in the class form. Vehicle is abstract class with Acceleration method. While you may/ may not provide any abstract method. But the business need is that Vehicle should not be instantiated. Hence you make it abstract. The other two classes - Ikon and FZ are concrete classes deriving from Vehicle class. These two will have their own properties and behaviours.
With regards to usage, using abstract on a class declaration but having no abstract members is the same as having the class public but using protected on its constructors. Both force the class to be derived in order for it to be instantiated.
However, as far as self-documenting code goes, by marking the class abstract it informs others that this class is never meant to be instantiated on its own, even if it has no virtual or abstract members. Whereas protecting the constructors makes no such assertion.
The compiler does not prevent implementation-logic, but in your case I would simply omit abstract ?! BTW some methods could be implemented with { throw Exception("must inherit"); } and the compiler could not distinguish fully implemented classes and functions including only throw.
Here's a potential reason:
Layer Supertype
It's not uncommon for all the objects
in a layer to have methods you don't
want to have duplicated throughout the
system. You can move all of this
behavior into a common Layer
Supertype.
-- Martin Fowler
There's no reason to prevent having only concrete methods in an abstract class - it's just less common. The Layer Supertype is a case where this might make sense.
I see abstract classes serving two main purposes:
An incomplete class that must be specialized to provide some concrete service. Here, abstract members would be optional. The class would provide some services that the child classes can use and could define abstract members that it uses to provide its service, like in the Template Method Pattern. This type of abstract class is meant to create an inheritance hierarchy.
A class that only provides static utility methods. In this case, abstract members don't make sense at all. C# supports this notion with static classes, they are implicitly abstract and sealed. This can also be achieved with a sealed class with a private constructor.

C# - Interface Clarification

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.

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