Exact use of Abstract class - c#

What is the exact use of an Abstract class? Is not possible to do the same things in an ordinary class as it is an an abstract class?

Use an abstract class to provide some concrete implementation but not allow instantiation. You can always instantiate an ordinary class which doesn't make sense if it can't stand alone. At the same time, an interface might not be enough if there's a concrete implementation that's identical in all implementing classes. An abstract class is just enough.
Interface: contract only, no implementation, no instantiation
Abstract class: contract, some implementation, no instantiation
Class: contract, implementation, instantiation

An abstract class is used when you have some base functionality that you want subclasses to inherit, but it wouldn't make sense to instantiate the base class. For example, if you had something like a Shape base class, you could have some built in implementation that could be used by subclasses as well as interface methods that you want the subclasses to implement. However, it probably wouldn't make sense to create a Shape object. An abstract class gives you this functionality. Another great example of abstract class uses is the abstract factory pattern.

Regular classes require you to provide implementations for all methods.
Interfaces require you to not provide any implementations for all methods.
Abstract classes are the only type of class that allow you to both have methods that do contain an implementation, and have methods that do not provide an implementation, but require an inheriting class to provide one.
The fact that you are allowed to add methods without an implementation is the reason you cannot instantiate an abstract class: you can only instantiate something that has implementations for all its methods.

Unlike regular classes, abstract classes can contain abstract methods. They act much like interface members.
Meanwhile, they can do just about everything else that regular classes can do: they can implement methods, contain fields & nested types, derive from another class, etc.

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.

Modeling questions (interface vs abstract class)

I have some doubts when to use abstract class and if I need to always code interface. An example:
I have will have series of custom entities, and all of them need to implement SomeMethod() and most of them need to implement AnotherMethod() method.
SomeMethod() will be entity specific, each entity will have different code.
AnotherMethod() is implemented by most, but not all, and the code is the same for all.
How is this modeled? My idea is that each new entity must implement SomeMethod() and is able to use AnotherMethod().
Thanks,
Goran
AnotherMethod should likely be implemented in an abstract class so you don't repeat the code all over the place.
If SomeMethod is related functionaloty, it could be left in the same abstract class without an implementation, forcing children to implement it. If the functionality is not related to AnotherMethod, you could put it in its own interface.
You're right, for SomeMethod(), using abstract parent class with abstract method is a good idea. You can also use interfaces, depending on the meaning of the method. For example, if different classes represent different animals and the method is Move(Coordinate destination), an abstract parent class is better. If, on the other hand, different classes have nothing in common and the method is SerializeToJSON(), you should better use interfaces.
If AnotherMethod() is implemented by some of the classes, again, you can use an abstract parent class (with a non-abstract protected/public method). Of course, don't inherit from this parent the classes which do not have to implement AnotherMethod().
A big difference between interfaces and abstract classes is that the abstract class can have some implementation where the interface is strictly a contract and data type. In the examples you give, you could use an interface to require the implementation of both SomeMethod and AnotherMethod but you wouldn't be able to write any code for AnotherMethod since the interface would just have a method signature.
In an abstract class you could define SomeMethod as abstract and therefore require an implementation from classes which inherit from it but you could also create the implementation of AnotherMethod and have a single implmentation since you say that it will be the same for a lot of your classes.
A good situation to think of replacing inheritance with aggregation.
I'd extract AnotherMethod() to other class, say, AnotherMethodRunner, and add a getAnotherMethodRunner() to a base interface. If AnotherMethod() is a property of derived class, it will have one, if not - it will return null or Null Object.
I personally usually take a nonempty abstract base class as a call to more precise interface extraction.

is an abstract class a type of interface?

In my /interfaces folder I put all my interfaces.
Is an abstract class a type of interface?
The answers which describe the technical differences are correct, but there's more than that. There's also a semantic difference.
The difference between an interface and an abstract class is that an interface represents the ability to do something, whereas an abstract class represents the commonalities of a class of objects.
The IDisposable interface represents the concept "I know how to dispose of my important resources"; that's something the object can do, not something the object is.
By contrast, if you were to make an abstract class Animal, then that would represent the common features of all animals. There are no objects in the world that are "animal" without being some more specific kind of animal -- golden retriever, king salmon, lion, whatever. We represent this fact by making the class abstract.
In C#, interfaces are distinct from classes (even abstract classes);
interfaces can only define the API (method signatures, event declarations, property declarations), not the implementation (fields, method bodies, etc)
you can only inherit one base class, but you can implement multiple interfaces
But they have similarities in some usages - for example when used in an abstract factory implementation.
No. There are several differences. The main difference is that there can be implementation details in an abstract class. A class can only derive from one (abstract) class, but it can implement multiple interfaces. An abstract class can contains fields while an interface can not. Lastly, interfaces can not have access modifiers on the declared methods, but abstract classes can.
No. An abstract class should include implementation of something, so it is more than just an interface.
A class with all abstract methods could be viewed as a kind of interface, but, at that point why wouldn't you just use an interface instead?

Interface or abstract class?

For my new Pet-Project I have a question for design, that is decided already, but I want some other opinions on that too.
I have two classes (simplified):
class MyObject
{
string name {get;set;}
enum relation {get;set;}
int value {get;set;}
}
class MyObjectGroup
{
string name {get;set;}
enum relation {get;set;}
int value {get;set;}
List<MyObject> myobjects {get;set;}
}
Later in the Project MyObjectGroup and MyObject should be used equally. For this I could go two ways:
Create an interface: IObject
Create an abstract class: ObjectBase
I decided to go the way of the interface, that I later in code must not write ObjectBase every time but IObject just for ease - but what are other positives for this way?
And second, what about adding IXmlSerializable to the whole story?
Let the interface inherit from IXmlSerializable or does it have more positives to implement IXmlSerializable in abstract base class?
Generally speaking, the approach I use in this kind of situation is to have both an interface and an abstract class. The interfaces defines, well, the interface. The abstract class is merely a helper.
You really can't go wrong with this approach. Interfaces give you the flexibility to change implementation. Abstract classes give you boilerplate and helper code that you aren't forced to use, which you otherwise would be if your methods were defined in terms of an abstract class explicitly.
These are some of the differences between Interfaces and Abstract classes.
1A. A class may inherit (Implement) one or more interfaces. So in C#, interfaces are used to achieve multiple inheritance.
1B. A class may inherit only one abstract class.
2A. An interface cannot provide any code, just the signature.
2B. An abstract class can provide complete, default code and/or just the details that have to be overridden.
3A. An interface cannot have access modifiers for the subs, functions, properties etc everything is assumed as public.
3B. An abstract class can contain access modifiers for the subs, functions, properties.
4A. Interfaces are used to define the peripheral abilities of a class. For eg. A Ship and a Car can implement a IMovable interface.
4B. An abstract class defines the core identity of a class and there it is used for objects.
5A. If various implementations only share method signatures then it is better to use Interfaces.
5B. If various implementations are of the same kind and use common behaviour or status then abstract class is better to use.
6A. If we add a new method to an Interface then we have to track down all the implementations of the interface and define implementation for the new method.
6B. If we add a new method to an abstract class then we have the option of providing default implementation and therefore all the existing code might work properly.
7A. An interface can not have fields defined.
7B. An abstract class can have fields and constants defined.
8A. An interface can not have constructor.
8B. An abstract class can have default constructors implemented.
9A. An interface can only inherit from other interfaces.
9B. An abstract class can inherit from interfaces, abstract class, or even class.
The interface would be my default until there is a reason to use a base class, as it makes fewer decisions for us.
I wouldn't involve IXmlSerializable unless I had to though; it is a messy, tricky interface that is often a cause of woe.
What exactly are your serialization requirements? There may be better options... however, for many serializers a base-class would be easier than an interface. For example, for XmlSerializer you could have:
[XmlInclude(typeof(MyObject))] // : ObjectBase
[XmlInclude(typeof(MyObjectGroup))] // : ObjectBase
public abstract class ObjectBase { /* */ }
(the exact approach depends on the serializer)
Generally, you should consider interfaces as contracts that some types implement and abstract classes as nodes in inheritance hierarchy that don't exist by themselves (i.e. there is an "is a" relationship between the derived class and the base abstract class). However, in practice, you might need to use interfaces in other cases, like when you need multiple inheritance.
For instance, IXmlSerializable is not an "entity" by itself. It defines a contract that an entity can implement. Interfaces live "outside" the inheritance hierarchy.
An Interface will allow you to define a 'contract' that the object will need to fulfil by delivering properties and methods as described by the interface. You can refer to objects by variables of interface-type which can cause some confusion as to what exactly is being offered.
A base class offers the opportunity to build an inheritance 'tree' where more complex classes (of a common 'type') are built on the foundations of a simpler 'base' classes. The classic and annoying example in OO is normally a base class of 'Shape' and which is inherited by Triangle, Square, etc.
The main point is that with an Interface you need to provide the entire contract with every class that implements it, with an inheritance tree (base classes) you are only changing/adding the properties and methods that are unique to the child class, common properties and methods remain in the base class.
In your example above I'd have the 'MyObjectGroup' object inherit the base 'MyObject' class, nothing to be gained from an interface here that I can see.
There are two thing is in Architect’s mind when designing classes.
Behavior of an object.
object’s implementation.
If an entity has more than one implementation, then separating the behavior of an object from its implementation is one of the key for maintainability and decoupling.
Separation can be achieved by either Abstract class or Interface but which one is the best? Lets take an example to check this.
Lets take a development scenario where things (request, class model, etc) are changing very frequently and you have to deliver certain versions of application.
Initial problem statement : you have to create a “Train” class for Indian railway which has behavior of maxSpeed in 1970 .
1. Business Modeling with abstract class
V 0.0 (Initial problem)
Initial problem statement : you have to create a Train class for Indian railway which has behavior of maxSpeed in 1970 .
public abstract class Train {
public int maxSpeed();
}
V 1.0 (Changed problem 1)
changed problem statement : You have to create a Diesel Train class for Indian railway which has behavior of maxSpeed, in 1975.
public abstract class DieselTrain extends train {
public int maxFuelCapacity ();
}
V 2.0 (Changed problem 2)
chanded problem statement : you have to create a ElectricalTrain class for Indian railway which has behavior of maxSpeed , maxVoltage in 1980.
public abstract class ElectricalTrain extends train {
public int maxvoltage ();
}
V 3.0 (Changed problem 3 )
chanded problem statement : you have to create a HybridTrain (uses both diesel and electrcity) class for Indian railway which has behavior of maxSpeed , maxVoltage,maxVoltage in 1985 .
public abstract class HybridTrain extends ElectricalTrain , DisealTrain {
{ Not possible in java }
}
{here Business modeling with abstract class fails}
2. Business Modeling with interface
Just change abstract word to interface and ……
your Business Modeling with interface will succeeds.
http://javaqna.wordpress.com/2008/08/24/why-the-use-on-interfaces-instead-of-abstract-classes-is-encouraged-in-java-programming/
Interface:
If your child classes should all implement a certain group of methods/functionalities but each of the child classes is free to provide its own implementation then use interfaces.
For e.g. if you are implementing a class hierarchy for vehicles implement an interface called Vehicle which has properties like Colour MaxSpeed etc. and methods like Drive(). All child classes like Car Scooter AirPlane SolarCar etc. should derive from this base interface but provide a seperate implementation of the methods and properties exposed by Vehicle.
–> If you want your child classes to implement multiple unrelated functionalities in short multiple inheritance use interfaces.
For e.g. if you are implementing a class called SpaceShip that has to have functionalities from a Vehicle as well as that from a UFO then make both Vehicle and UFO as interfaces and then create a class SpaceShip that implements both Vehicle and UFO .
Abstract Classes:
–> When you have a requirement where your base class should provide default implementation of certain methods whereas other methods should be open to being overridden by child classes use abstract classes.
For e.g. again take the example of the Vehicle class above. If we want all classes deriving from Vehicle to implement the Drive() method in a fixed way whereas the other methods can be overridden by child classes. In such a scenario we implement the Vehicle class as an abstract class with an implementation of Drive while leave the other methods / properties as abstract so they could be overridden by child classes.
–> The purpose of an abstract class is to provide a common definition of a base class that multiple derived classes can share.
For example a class library may define an abstract class that is used as a parameter to many of its functions and require programmers using that library to provide their own implementation of the class by creating a derived class.
You could actually go with BOTH. ObjectBase saves you the trouble of implementing the common properties more than once and implements IObject for you. Everywhere you use it refer to IObject so you can do testing with mocks later
I'd rather go for base abstract class, because, theoretically (well, it's just one theory, I'm not proving or saying that any other is worse then this) - interfaces should be used, when you want to show, that some object is capable of doing something (like IComparable - you show that whatever implements it, can be compared to something else), whereas when you have 2 instances that just share something common or have 1 logical parent - abstract classes should be used.
You could also go for both approaches, using base class, that will implement an interface, that will explicitly point what your class can do.
Note that you cannot override operators in Interfaces. That is the only real problem with them as far as I'm concerned.
All else being equal, go with the interface. Easier to mock out for unit testing.
But generally, all I use base classes for is when there's some common code that I'd rather put in one place, rather than each instance of the derived class. If it's for something like what you're describing, where the way they're used is the same, but their underlying mechanics are different, an interface sounds more appropriate.
I've been using abstract classes in my projects, but in future projects, I'll use interfaces.
The advantage of "multiple inheritance" is extremely useful.
Having the ability to provide a completely new implementation of the class, both in code, or for testing purposes, is always welcome.
Lastly, if in the future you'll want to have the ability to customize your code by external developers, you don't have to give them your real code - they can just use the interfaces...
If you have function in class,you should use abstact class instead of interface.
In general,an interface is used to be on behalf of a type.
Choosing interfaces and abstract classes is not an either/or proposition. If you need to change your design, make it an interface. However, you may have abstract classes that provide some default behavior. Abstract classes are excellent candidates inside of application frameworks.
Abstract classes let you define some behaviors; they force your subclasses to provide others. For example, if you have an application framework, an abstract class may provide default services such as event and message handling. Those services allow your application to plug in to your application framework. However, there is some application-specific functionality that only your application can perform. Such functionality might include startup and shutdown tasks, which are often application-dependent. So instead of trying to define that behavior itself, the abstract base class can declare abstract shutdown and startup methods. The base class knows that it needs those methods, but an abstract class lets your class admit that it doesn't know how to perform those actions; it only knows that it must initiate the actions. When it is time to start up, the abstract class can call the startup method. When the base class calls this method, Java calls the method defined by the child class.
Many developers forget that a class that defines an abstract method can call that method as well. Abstract classes are an excellent way to create planned inheritance hierarchies. They're also a good choice for nonleaf classes in class hierarchies.
The definition of the abstract class may describe code and state, and classes that derive from them may not derive from other classes at the same time. That's what the technical difference is.
Therefore, from the point of view of usage & philosophy, the difference is that by setting up an abstract class, you constrain any other functionality that the objects of that class may implement, and provide those objects with some basic functionality that is common for any such object (which is a kind of constraint, too), while by setting up an interface, you set up no constraints for other functionality and make no real-code provisions for that functionality which you have in mind. Use the abstract classes when you about know everything that objects of this class are supposed to be doing for the benefit of their users. Use the interfaces when the objects might also do something else that you can't even guess by now.

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