I'm developing a reusable library and have been creating abstract classes, so the client can then extend from these.
QUESTION: Is there any reason in fact I should use an abstract class here as opposed to just a normal class?
Note - Have already decided I do not want to use interfaces as I want to include actual default methods in my library so the client using it doesn't have to write the code.
EDIT: So I'm fishing for any advantages I can't think of. For example when upgrading the library would use of an abstract class lessen impact on client code - I can't see it would in this case no?
Unless you want to force the end users to inherit from your classes, there should be no reason to use abstract.
If you want to make your classes inheritable and easily extensible, use virtual on your methods and make sure you have usable protected constructors.
The motivation for the abstract class is to require clients to override the class. Your decision on whether the class should be abstract or not depends primarily on whether the abstract is missing some fundamental behavior that only an user of the class can supply.
You can usually tell you need your class to be abstract if you use a template method of some sort, where "plug in the hole in this behavior" completes the logic of he class. If your class is useful without some user-supplied logic, you probably don't need the class to be abstract.
As an example, frameworks usually can't make decisions on behalf of their users in terms of things like object state validation, printing, display, and so on, and they would need to defer to concrete implementations by the clients.
The difference between an abstract class and a non-abstract one is that you can't instantiate the former and it MUST be overriden. It is really up to you to determine whether or not an instance of the base class makes sense on its own.
Let me show you two cases. One is where abstract class makes sense and one where it doesn't.
public abstract class Animal {
public string Name {get;set;}
}
public class Dog : Animal {
public Bark(){}
}
public class Cat : Animal {
public Meaow(){}
}
In this scenario we have a common base Animal that provides implementation for Name property. It makes no sense to instantiate Animal by itself as there are no animals in the world that are just animals, they are wither dogs or cats or something else.
Here is a case where it makes sense to have a non-abstract base.
class Path {
public Path(IList<Point> points) {
this.Points = new ReadOnlyCollection<Point>(points);
}
public ReadOnlyCollection<Point> Points {get;}
}
class RectanglePath : Path{
public SquarePath (Point origin, int height, int width) :
base(new List<Point>{origin, new Point(origin.X + width, point.Y}, ....){
}
}
Here Path that is not subclassed makes sense, we can create any arbitrary shape, but it might be more convenient to use a sublass for more specific shapes.
Sounds like you are a little confused about the difference between a virtual method and an abstract class. You don't need to mark your class as abstract unless you determine that it doesn't make sense on it's own. This is useful in areas where you might have shared behaviors between multiple classes.
Sounds to me like you just need a regular class and some methods that are virtual.
Related
Inspired by a great video on the topic "Favor object composition over inheritance" which used JavaScript examples; I wanted to try it out in C# to test my understanding of the concept, but it didn't go as well as I'd hoped.
/// PREMISE
// Animal base class, Animal can eat
public class Animal
{
public void Eat() { }
}
// Dog inherits from Animal and can eat and bark
public class Dog : Animal
{
public void Bark() { Console.WriteLine("Bark"); }
}
// Cat inherits from Animal and can eat and meow
public class Cat : Animal
{
public void Meow() { Console.WriteLine("Meow"); }
}
// Robot base class, Robot can drive
public class Robot
{
public void Drive() { }
}
The problem is that I want to add RobotDog class that can Bark and Drive, but not eat.
First solution was to create RobotDog as subclass of Robot,
public class RobotDog : Robot
{
public void Bark() { Console.WriteLine("Bark"); }
}
but to give it a Bark function we had to copy and paste the Dog's Bark function so now we have duplicate code.
The second solution was to create a common super class with a Bark method that then both the Animal and Robot classes inherited from
public class WorldObject
{
public void Bark() { Console.WriteLine("Bark"); }
}
public class Animal : WorldObject { ... }
public class Robot : WorldObject { ... }
But now EVERY animal and EVERY robot will have a Bark method, which most of them don't need. Continuing with this pattern, the sub-classes will be laden with methods they don't need.
The third solution was to create an IBarkable interface for classes that can Bark
public interface IBarkable
{
void Bark();
}
And implement it in the Dog and RobotDog classes
public class Dog : Animal, IBarkable
{
public void IBarkable.Bark() { Console.WriteLine("Bark"); }
}
public class RobotDog : Robot, IBarkable
{
public void IBarkable.Bark() { Console.WriteLine("Bark"); }
}
But once again we have duplicate code!
The fourth method was to once again use the IBarkable interface, but create a Bark helper class that then each of the Dog and RobotDog interface implementations call into.
This feels like the best method (and what the video seems to recommend), but I could also see a problem from the project getting cluttered with helpers.
A fifth suggested (hacky?) solution was to hang an extension method off an empty IBarkable interface, so that if you implement IBarkable, then you can Bark
public interface IBarker { }
public static class ExtensionMethods
{
public static void Bark(this IBarker barker) {
Console.WriteLine("Woof!");
}
}
A lot of similar answered questions on this site, as well as articles I've read, seem to recommend using abstract classes, however, wouldn't that have the same issues as solution 2?
What is the best object-oriented way to add the RobotDog class to this example?
At first if you want to follow "Composition over Inheritance" then more than half of your solutions don't fit because you still use inheritance in those.
Actually implementing it with "Composition over Inheritance" there exists multiple different ways, probably each one with there own advantage and disadvantage. At first one way that is possible but not in C# currently. At least not with some Extension that rewrites IL code. One idea is typically to use mixins. So you have interfaces and a Mixin class. A Mixin basically contains just methods that get "injected" into a class. They don't derive from it. So you could have a class like this (all code is in pseudo-code)
class RobotDog
implements interface IEat, IBark
implements mixin MEat, MBark
IEat and IBark provides the interfaces, while MEat and MBark would be the mixins with some default implementation that you could inject. A design like this is possible in JavaScript, but not currently in C#. It has the advantage that in the end you have a RobotDog class that has all methods of IEat and IBark with a shared implementation. And the this is also a disadvantage at the same time, because you create big classes with a lot of methods. On top of it there can be method conflicts. For example when you want to inject two different interfaces with the same name/signature. As good as such an approach looks first, i think the disadvantages are big and i wouldn't encourage such a design.
As C# doesn't support Mixins directly you could use Extension Methods to somehow rebuilt the design above. So you still have IEat and IBark interfaces. And you provide Extension Methods for the interfaces. But it has the same disadvantages as a mixin implementations. All methods appear on the object, problems with method names collision. Also on top, the idea of composition is also that you could provide different implementations. You also could have different Mixins for the same interface. And on top of it, mixins are just there for some kind of default implementation, the idea is still that you could overwrite or change a method.
Doing that kind of things with Extensions Method is possible but i wouldn't use such a design. You could theoretically create multiple different namespaces so depending on which namespace you load, you get different Extension Method with different implementation. But such a design feels more awkward to me. So i wouldn't use such a design.
The typical way how i would solve it, is by expecting fields for every behaviour you want. So your RobotDog looks like this
class RobotDog(ieat, ibark)
IEat Eat = ieat
IBark Bark = ibark
So this means. You have a class that contains two properties Eat and Bark. Those properties are of type IEat and IBark. If you want to create a RobotDog instance then you have to pass in a specific IEat and IBark implementation that you want to use.
let eat = new CatEat()
let bark = new DogBark()
let robotdog = new RobotDog(eat, bark)
Now RobotDog would Eat like a cat, and Bark like a Dog. You just can call what your RobotDog should do.
robotdog.Eat.Fruit()
robotdof.Eat.Drink()
robotdog.Bark.Loud()
Now the behaviour of your RobotDog completely depends on the injected objects that you provide while constructing your object. You also could switch the behaviour at runtime with another class. If your RobotDog is in a game and Barking gets upgraded you just could replace Bark at runtime with another object and the behaviour you want
robotdog.Bark <- new DeadlyScreamBarking()
Either way by mutating it, or creating a new object. You can use a mutable or immutable design, it is up to you. So you have code sharing. At least me i like the style a lot more, because instead of having a object with hundreds of methods you basically have a first layer with different objects that have each ability cleanly separated. If you for example add Moving to your RobotDog class you just could add a "IMovable" property and that interface could contain multiple methods like MoveTo, CalculatePath, Forward, SetSpeed and so on. They would be cleanly avaible under robotdog.Move.XYZ. You also have no problem with colliding methods. For example there could be methods with the same name on each class without any problem. And on top. You also can have multiple behaviours of the same type! For example Health and Shield could use the same type. For example a simple "MinMax" type that contains a min/max and current value and methods to operate on them. Health/Shield basically have the same behaviour, and you can easily use two of them in the same class with this approach because no method/property or event is colliding.
robotdog.Health.Increase(10)
robotdog.Shield.Increase(10)
The previous design could slightly be changed, but i don't think it makes it better. But a lot of people brainlessly adopt every design pattern or law with the hope it automatically makes everything better. What i want to refer here is the often called Law-of-Demeter that i think is awful, especially in this example. Actually there exists a lot of discussion of whether it is good or not. I think it is not a good rule to follow, and in that case it also becomes obvious. If you follow it you have to implement a method for every object that you have. So instead of
robotdog.Eat.Fruit()
robotdog.Eat.Drink()
you implement methods on RobotDog that calls some method on the Eat field, so with what did you end up?
robotdog.EatFruit()
robotdog.EatDrink()
You also need once again to solve collisions like
robotdog.IncreaseHealt(10)
robotdog.IncreaseShield(10)
Actually you just write a lot of methods that just delegates to some other methods on a field. But what did you won? Basically nothing at all. You just followed brainless a rule. You could theoretically say. But EatFruit() could do something different or do something additional before calling Eat.Fruit(). Weel yes that could be. But if you want other different Eat behaviour then you just create another class that implements IEat and you assign that class to the robotdog when you instantiate it.
In that sense, the Law of Demeter is not a dot counting Exercise.
http://haacked.com/archive/2009/07/14/law-of-demeter-dot-counting.aspx/
As a conclusion. If you follow that design i would consider using the third version. Use Properties that contain your Behaviour objects, and you can directly use those behaviours.
I think this is more of a conceptual dilemma rather than a composition issue.
When you say :
And implement it in the Dog and RobotDog classes
public class Dog : Animal, IBarkable
{
public void IBarkable.Bark() { Console.WriteLine("Bark"); }
}
public class RobotDog : Robot, IBarkable
{
public void IBarkable.Bark() { Console.WriteLine("Bark"); }
}
But once again we have duplicate code!
If Dog and RobotDog have the same Bark() implementation, they should inherit from the Animal class. But if their Bark() implementations are different, it makes sense to derive from IBarkable interface. Otherwise, where is the distinction between Dog and RobotDog?
I have following problem:
I am creating an aplication for creating UML diagrams. Right now just to simplify everything I assume only couple of available diagram elements:
class
interface
generalization
interface implementation
association
aggregation
I decided to create one common abstract class for all of that elements:
abstract DiagramElement which has 2 subclasses also abstract:
DiagramRelation
DiagramObject
Nextly DiagramRelation has 4 subclasses:
Generalization
InterfaceImplementation
Assosication
Aggregation
And DiagramObject has 2 subclasses:
Interface
Class
I really wanted to post a picture so it would be all much more simplier but I don't have enough reputation points so sorry.
I came across following problem: each of this element have a different visual representation, ie: interface has only methods etc so each of this element will need to be show differently - I don't want to use multiple "if" instructions for it.
I use WPF and I decided that every control will place it's contest into StackPanel which will be placed inside MyContextControl (inherits after ContextControl and add interface atribute):
public interface IDiagramElementDraw
{
public StackPanel Draw();
}
public MyContextControl : ContextControl
{
private IDiagramElementDraw _drawingInterface;
private StackPanel context;
public DrawControl()
{
context = _drawingInterface.Draw();
}
}
But I don't know which class should implement IDiagramElementDraw interface - I don't want to implement it at the level of Interface, Class, Generalization etc classes because I want them to only represent logical information about each element.
I would appreciate any help, feel free to post complete different solution - this one may be completely wrong, this was just my idea.
From my answer to another question:
Distinction between using an interface or an abstract class as a
basis: An abstract class ia a shared implementation; an interface is a
shared contract. They share some commonality, but meet different
requirements. For instance, you might want to share requirements (a
common interface IProjectile) between small arms and heavier weapons,
or between lethal and non-lethal weapons, while implementing the three
categories on three distinct abstract classes (LethalSmallArms,
NonLethalSmallArms, and Howitzers) that all implement the common
interface IProjectile.
From another answer of mine
An abstract class can, with care, be extended in a non-breaking
manner; all changes to an interface are breaking changes.
Update: In contrast, an interface can be an in or out type-parameter
and an abstract class cannot. Sometimes one or the other is more
appropriate for a given design, and sometimes it is a toss-up.
Generally speaking, both interfaces and abstract classes are useful; it just depends on WHO:
Interfaces are more desirable for someone to USE your API, for they
gurantee him with absolute freedom.
Abstract classes are more
desirable for someone to EXTEND your API, for they ease the task of
extending.
The more sensitive option is to combine both: Desing a hierarchy of public interfaces (for using), and provide also abstract classes with the members mostly common to any implementation (for extending), and if you want to let the client extend your API, make them public.
And, in the bottom of all the hierarchy, private implementation classes are expected.
Using polymorphism could be a good solution and will prevent "if" conditions.
1. You could have an IDrawable interface that will have a Draw method on it.
This interface will be implemented by you abstract class.
2. Then you will have an ElementDrawing and its derived classes which will draw the different types (classes, interfaces,...). It could be a virtual property that will be instantiated in each DiagramElement differently according to the type.
class abstract DiagramElement : IDrawable
{
public abstract void Draw();
}
class ClassDiagramElement:DiagramElement
{
public overrides void Draw()
{
ElementDrawing elementDrawing = new ClassDrawing();
elementDrawing.DrawElement();
}
}
class InterfaceDiagramElement:DiagramElement
{
public overrides void Draw()
{
ElementDrawing elementDrawing = new InterfaceDrawing();
elementDrawing.DrawElement([maybe need some parameters]);
}
}
ElementDrawing is a base class for all the derived classes that draw the different elements in your UML. It can be defined as virtual property as mentioned above.
Let's suppose I have a widget class:
struct Widget {
public Color Color { get; set; }
public int Frobbles { get; set; }
}
Now, I need to make a factory to create these widgets, so I build a WidgetFactory:
abstract class WidgetFactory {
public virtual Widget GetWidget();
}
As it turns out, you can make widgets out of several different materials, but the resulting widgets are pretty much the same. So, I have a few implementations of WidgetFactory:
class GoldWidgetFactory : WidgetFactory {
public GoldWidgetFactory(GoldMine goldmine) {
//...
}
public Widget GetWidget() {
Gold g = goldmine.getGold();
//...
}
}
class XMLWidgetFactory : WidgetFactory {
public XMLWidgetFactory(XmlDocument xmlsource) {
//...
}
public Widget GetWidget() {
XmlNode node = //whatever
//...
}
}
class MagicWidgetFactory : WidgetFactory {
public Widget GetWidget() {
//creates widget from nothing
}
}
My question is this: Should WidgetFactory be an abstract class, or an interface? I can see arguments in both directions:
Base class:
The implementations ARE WidgetFactories
They might be able to share functionality, (say, a List<Widget> WidgetFactory.GetAllWidgets() method)
Interface:
The implementations do not inherit any data or functionality from the parent
Their internal workings are completely different
Only one method is defined
To those answering, this does not (currently) parallel to any real-world problem, but if/when I need to implement this pattern, it would be good to know. Also, "it doesn't matter" is a valid answer.
Edit: I should point out why go through this in the first place. The hypothetical usage of this class hierarchy would be something like:
//create a widget factory
WidgetFactory factory = new GoldWidgetFactory(myGoldMine);
//get a widget for our own nefarious purposes
Widget widget = factory.GetWidget();
//this method needs a few widgets
ConsumeWidgets(factory);
So, having a GetGoldWidget() method in WidgetFactory is not a very good idea. Plus, perhaps advents in Widget technology allow us to add different and more exotic types of widgets in the future? It's easier and cleaner to add a new class to handle them than shoehorn a method into an existing class.
In the example that you have given WidgetFactory has absolutely no reason to be an abstract class since there are not shared attributes or methods between different implementations of the factory.
Even if there was shared functionality, it would be more idiomatic to make an interface and pass it around to the users of WidgetFactory, to reduce the mount of knowledge those components need to have about the factory.
The overall implementation is fine and is really an abstract factory pattern, the only addition I would do is IWidgetFactory:
public interface IWidgetFactory {
Widget GetWidget();
}
abstract class WidgetFactory : IWidgetFactory {
//common attributes and methods
}
//Defferent implementations can still inherit from the base abstract class
class GoldWidgetFactory : WidgetFactory {
public GoldWidgetFactory(GoldMine goldmine) {
//...
}
public Widget GetWidget() {
Gold g = goldmine.getGold();
//...
}
}
In this case I see no benefit to using an abstract class instead of an interface.
I would generally favour interfaces over abstract classes:
They don't use up your one opportunity at class inheritance
They can be easier to mock
They feel "purer" somehow (it's clear just from the interface what the implementer needs to provide; you don't need to check each method to see whether or not it's concrete, abstract, or virtual)
In this case, however, you could easily use a delegate as there's only a single method... basically a Func<Widget>.
I disagree with Larry's idea of just using a single factory to directly create all the widgets with separate methods - as you may want to pass the WidgetFactory as a dependency to another class which doesn't need to know about the source, but needs to call CreateWidget either at a different time or possibly multiple times.
However, you could have a single widget factory with multiple methods each returning a Func<Widget>. That would give the benefits of having a single factory class while also allowing for dependency injection of the "factory" notion.
Honestly, what ever else, besides the Concrete Factory classes, do you expect to inherit from WidgetFactory? Anything?... ever?
If not it probably doesn't ever matter.
If down the road you want to add common code between them all than an abstract class would be your best bet.
Also I don't really see the need for your factory methods to implement any other interface except that of your creation method. So it doesn't matter whether it's abstract or interface. It all comes down to whether in the future you will want to add additional functionality in the future to the abstract class.
You don't need inheritance or an interface or even more than one class. The single factory should make all different kinds of widgets ; you can just pass in the materials as a parameter to the create method. The idea is to hide the aspects of different construction of objects from the caller - by making a bunch of different classes you are exposing this, not hiding it.
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.
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.