What to use here, abstract class or Interface? [duplicate] - c#

This question already has answers here:
When to use an interface instead of an abstract class and vice versa?
(26 answers)
Closed 8 years ago.
I have an abstract class say CTest which contains only the abstract method f1() and nothing else. Similiarly, i have a Interface ITest with the only method f1(). Here both the CTest abstract class and ITest interface does the same thing.
The one difference is that, the Interface provides the flexibility that it can be implemented in any classes which already derived from other class but abstract classes cannot.
Apart from the above difference, What is the actual difference between these two? and which one is efficient here(CTest or ITest)? When i should use what? Any specific scenario's in OO Design and any general suggessions on this are helpful

Other than inheritance, it depends on the scenario. Check this code project article with an excellent example.
[From the article]
Lets Assume you need to make three classes, first is CAR, second is
MAN, third is WOMAN. Now you need a function in each of them to define
how they Move. Now all three can move but CAR moves entirely in
different way than MAN and WOMAN. So here we use an Interface
IMOVEMENT and declare a function MOVE in it. Now all three classes can
inherit this interface. So the classes goes like this.
public interface IMovement
{
void Move();
}
public class Car : IMovement
{
public void Move()
{
//Provide Implementation
}
}
public class Man : IMovement
{
public void Move()
{
//Provide Implementation
}
}
public class Woman : IMovement
{
public void Move()
{
//Provide Implementation
}
}
But, since MAN and WOMAN walk in similar way, so providing same
behavior in two different methods will be code redundancy, in simpler
words code is not re-used. So we can now define a Abstract Class for
Human Beings movements, so this class can be HUMANBEINGMOVEMENT. Also
the same can be applied to CAR class, since there are lot of
manufactures for cars and all cars move in similar way so we can also
define a abstract class for Cars movement which can be CARSMOVEMENT.
So our refactored code will be .
public interface IMovement
{
void Move();
}
public abstract class CarsMovement : IMovement
{
public virtual void Move()
{
//default behavior for cars movement
}
}
public class SuzukiCar : CarsMovement
{
public override void Move()
{
//Provide Implementation
}
}
public abstract class HumanBeingMovement : IMovement
{
public virtual void Move()
{
//default behavior for human being movement
}
}
public class Man : HumanBeingMovement
{
public override void Move()
{
//Provide Implementation
}
}
public class Woman : HumanBeingMovement
{
public override void Move()
{
//Provide Implementation
}
}

In Java prefer Interfaces to Abstract Classes. Refer Item 18 in Effective Java
Main Points :
Existing classes can be retroffited to implement a new interface.
Interfaces are ideal for defining mixins.
Interfaces allow the construction of nonheirarchical type frameworks.
Interfaces enable safe, powerful functionality enhancements.

in c# it allows only single level inheritance. therefore interfaces can be use to do multiple inheritances
and also for more details :
http://www.dotnetfunda.com/forums/thread4085-difference-between-interface-and-abstract-class.aspx
http://sadi02.wordpress.com/2008/05/08/what-is-difference-in-an-abstract-class-and-an-interface/

For me it better to use interface here. Abstract class should be used when you could extract some code there (you could implement method or there is other stuff that want to invoke it).

In this case there is no difference but CTest class has the only class which could be inherited as a Class . However ITest interface can be inherited by other class and interface at the same time.

In the scenario you have mentioned, that there is only one method, which will have no definition, the best way to go for is interface.
The major advantage an interface gives in Java that you can implement more than one interfaces, but you can extend only one class. So if you are already extending the one abstract class, you are not left with an option of extending any other class.
Golden rule: Interface is better than abstract class if we only need
to define methods and not declare them.
Having said that an interface is better in your case, a programmer should also think of his code from a future perspective. Do you feel the class/ interface you are creating will have more methods in future. Would you like to define those methods or just declare? Answer to these question will let you know if an interface is sufficient or will need an abstract class.

Advantage:
Implementation of Abstract class is better than Interface because method looking up of abstract class is fast than interface. If you modify your interface , you have to update your implementation class but any modification of abstract class , no effect on implementation class.
disadvantage:
If you want to implement more than one parent class method , it is not possible.
But regarding to interface you can implement more than one.

In this case, and assuming that your Abstract Class will only contain abstract methods, you should, in my opinion, go with the Interface. Abstract classes with abstract methods and interfaces serve the same purpose, however, you can extend only one class but implement as many as you want, thus making your code less prone to significant changes should you decide the inherit some functionality from some other class.
Regarding your question: But What is the actual difference between these two? and which one is efficient here(CTest or ITest)? When i should use what? Any specific scenario's in OO Design and any general suggessions on this are helpful
Interfaces are similar to contracts, when a class implements an interface, it guarantees an implementation. This is usually helpful when someone wants to provide functionality but does not want to reveal internal code, so the developer will just throw out the interface so that you can make your calls without knowing how is each method implemented. You can obviously implement as many interfaces as you like.
Abstract classes allow you to create a class which has certain behaviours which are specified and some others which are left to be implemented in the future. Unlike interfaces however, each class can only extend one class, so you should extend classes with caution from this point of view. Abstract classes also allow you to inject behaviour to one class and have it automatically spread through its child classes. This usually makes certain sections of development/maintenance easier.

Related

Can we use Abstract class instead of interface [duplicate]

This question already has answers here:
Interface vs Abstract Class (general OO)
(36 answers)
Closed 7 years ago.
i have started career as support developer but i have dream to get a job for S/W dev.
i am learning OOPS with C#. often one thing bug me that is interface and abstract class usage. when to use interface and when to use abstract class. i search google on this topic but whatever the answer i browse and i saw all people try to explain what is abstract and interface but i am not after their definition rather i want see their real usage in real world program. here i like to highlight one code where interface is used but i think the full things can be design with abstract class too.
see the below code of repository design pattern where interface has been used
if i expose repository as interface
public interface IEmployeeRepository
{
Employee[] GetAll();
}
then advantage will be i could have as many implementations as i like as below
public class EmployeeRepositoryEF: IEmployeeRepository
{
public Employee[] GetAll()
{
//here you will return employees after querying your EF DbContext
}
}
public class EmployeeRepositoryXML: IEmployeeRepository
{
public Employee[] GetAll()
{
//here you will return employees after querying an XML file
}
}
public class EmployeeRepositoryWCF: IEmployeeRepository
{
public Employee[] GetAll()
{
//here you will return employees after querying some remote WCF service
}
}
see the above code which has one contract method GetAll()
and who ever will extend the interface then they can provide their own implementation. that is the advantage but my question can i write abstract class instead of interface here ?
suppose i have one abstract class
abstract class AbsEmployeeRepository
{
abstract public Employee[] GetAll();
}
now my all other repository will extend the abstract class AbsEmployeeRepository
and override the function GetAll() to give their own implementation.
now the question is if abstract class can solve my purpose then why we need interface in this scenario. where multiple inheritance is concern then interface will be preferred other wise we can complete job with abstract class.
looking for valuable comments and suggestions. thanks
You would use an abstract class, when you have
Code to be shared.
Default behaviour in methods, but want users of your class to be able to override it.
You would use an interface when
There is no shared code.
It needs to be applied to many objects, with no common base class.
To make the definitions of public methods clearer and provide documentation.
You wish the source code to be private.
Often you would use an abstract class (for shared code) together with an interface (for documentation).
Interface provides only "description" of your future classes, while abstract classes used when you need to have some "unfinished functionality". So if you want to have a class with some logic provided and some unimplemented functions - you should use abstract class, but if all the functions is not implemented - use interface instead.
You should use an abstract class IF all your implementation share a common code basis implementation. That means, the interface will guarantee, that all classes have the same members, but each one must have its own implementation for them.
If you have an abstract class as base, all inheriting classes share the same implementation unless they override it, which is in many cases not needed, often you need to implement only a hand full of members differently.
Interface - guarantee same members.
Abstract class - share common code basis.
Some nice thoughts about it got mentioned on my question for this, maybe this helps you out.
You use abstract classes when you need to provide more than just abstract members to implement but also some concrete member:
public abstract class A
{
protected abstract void DoSomeCheck();
public void DoStuff()
{
// You don't know how DoSomeCheck will be implemented but
// you know a derived class must implement it
DoSomeCheck();
}
}
Alternatively, you use interfaces to define contracts that must be fulfilled by implementers in order to ensure that they can work together with your code:
// This car accepts any engine that implements IEngine
public class Car
{
public IEngine Engine { get; set; }
}
public interface IEngine
{
void Start();
}
There're many other use cases for both abstract classes and interfaces, but covering them would require a to compose a book instead of a simple answer. I still think that above explanation should give you the required hint to learn more about the topic.
can i write abstract class instead of interface here ?
Technically, yes you can. Practically, you shouldn't.
In this particular case implementation of the repositories is likely to be different. If implementation is different, an interface will declare desired behaviour in a clear way. Use of an abstract class can be justified, if the implementation was the same for all your repositories, or some methods where the same. Therefore allowing you to move otherwise duplicated code into one shared place.
In your particular case I'd rather not use either tailored interface or abstract class. There's IEnumerable<T> that does all you want, do not re-invent the wheel:
public class EmployeeRepositoryEF: IEnumerable<Employee> {
...
}
public class EmployeeRepositoryXML: IEnumerable<Employee> {
...
}
whenever you want an array all you need do is ToArray():
EmployeeRepositoryEF myRepo = ...
Employee[] staff = myRepo.ToArray(); // <- just ask for array

Design/Patterns - should I use interfaces or abstract classes?

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.

Difference between Interface and Abstract class in terms of Decoupling?

As we know there are basically two important difference between Interface and Abstract class.
We can have function definitions in abstract class. This is advantageous when we want to add a function in a class without need to track down it's all implementations.
We can have multiple interface implementation.
I just came to know that we can differentiate between them in terms of Decoupling?
Your comments...
Also if you can you provide a very basic link that explains the Decoupling for Interface and Abstract class ?
We normally use Business Logic Layer, Data Access Layer(contains abstract functions) and DataAccess.SqlServer Layer. Right? Despite of the fact that we aware of the Business needs, why are we creating Data Access Layer(contains abstract functions), Why can't Business Logic layer directly access DataAccess.SqlServer Layer?
Decoupling
In programming and design, this is generally the act of making code which is re-usable with as few dependencies as possible.
Factory Pattern In This Context
When using the Factory Pattern, you have a centralized factory which can create objects without necessarily defining them itself. That would be up to the object's definition.
Abstract and Interface
Interface
Defining an interface is best practice, as it allows for a light weight type to be used for inference, and also provides a blueprint which all inheriting classes must abide by. For example, IDisposable must implement the Dispose method. Note that this is decoupled from the interface, as each class inheriting IDisposable will define its own function of the Dispose method.
Abstract
Abstract is similar to interface in that it is used for inheritance and inference, but it contains definitions which all classes will inherit. Something to the extent of every automobile will have an engine so a good abstract class for automobile could include a predefined set of methods for an engine.
Edit
Explanation
Here you will see a simple example of inheritance using an interface and an abstract class. The decoupling occurs when the interface is inherited by an abstract class and then it's methods are customized. This allows for a class to inherit the abstract class and still have the same type as the interface. The advantage is that the class inheriting the abstract class can be used when the expected type is the original interface.
Decoupling
That advantage allows for any implementation to be used which conforms to the expected interface. As such, many different overloads can be written and passed in. Here is an example of one.
Example
Interface Definition
public interface IReady
{
bool ComputeReadiness();
}
Inheritance
public abstract class WidgetExample : IReady
{
public int WidgetCount { get; set; }
public int WidgetTarget { get; set; }
public bool WidgetsReady { get; set; }
public WidgetExample()
{
WidgetCount = 3;
WidgetTarget = 45;
}
public bool ComputeReadiness()
{
if (WidgetCount < WidgetTarget)
{
WidgetsReady = false;
}
return WidgetsReady;
}
}
public class Foo : WidgetExample
{
public Foo()
{
this.WidgetTarget = 2;
}
}
public class Bar : IReady
{
public bool ComputeReadiness()
{
return true;
}
}
Decoupling
public class UsesIReady
{
public bool Start { get; set; }
public List<string> WidgetNames { get; set; }
//Here is the decoupling. Note that any object passed
//in with type IReady will be accepted in this method
public void BeginWork(IReady readiness)
{
if (readiness.ComputeReadiness())
{
Start = true;
Work();
}
}
private void Work()
{
foreach( var name in WidgetNames )
{
//todo: build name
}
}
}
Polymorphism
public class Main
{
public Main()
{
//Notice that either one of these implementations
//is accepted by BeginWork
//Foo uses the abstract class
IReady example = new Foo();
UsesIReady workExample = new UsesIReady();
workExample.BeginWork(example);
//Bar uses the interface
IReady sample = new Bar();
UsesIReady workSample = new UsesIReady();
workSample.BeginWork(sample);
}
}
I've been looking through the answers, and they all seem a little complicated for the question. So here is my (hopefully) simpler answer.
Interface should be used when none of the implementation details are available to the current scope of the code.
Abstracts should be used when some of the implementation details are available to you
And, for completeness, when all of the implementation details are available you should be using classes.
In terms of decoupling, while I somewhat agree with Shelakel, for the purposes of this question, and stating fully decoupled design practices, I would suggest the following:
Always use Interfaces to define external behaviour.
When you have some of the implementation details available, use
abstract classes to define them, but implement the interfaces on
the abstract classes, and inherit from those classes in turn.
This ensures that later if you need to change some obscure implementation detail in a new implementation you are able to do so without modifying the existing abstract class, and are also able to group different implementation types into different abstract classes.
EDIT: I forgot to include the link :)
http://www.codeproject.com/Articles/11155/Abstract-Class-versus-Interface
Abstract classes and interfaces are not MUTUALLY EXCLUSIVE choices. I often define both an Interface and an abstract class that implements that interface.
The interface ensure the maximum decoupling because it doesnt force your class to belong to a specific inheritance hierarchy, so your class may inherit from whichever other class. In other terms any class can inherit from an Interface, while classes that already inherits from other classes cannot inherit from an abstract class.
On the other side in an abstract class you can factor out code that is common to all implementations, while with Interfaces you are forced to implement everything from the scratch.
As a conclusion, often the best solution is using BOTH an abstract class and an Interface, so one can move from re-using the common code contained in the abstract class, if possible, to re-implementing the interface from the scratch, if needed.
Decoupling for the sake of decoupling is a futile exercise.
Interfaces are meant to be used for integration where the specifics aren't required to be known to be of use (ex. SendEmail()). Common uses include components, services, repositories and as markers for IOC and generic implementations.
Extension methods with generic type constraints that include interfaces allow functionality similar to traits found in Scala with similar composability.
public interface IHasQuantity { double Quantity { get; } }
public interface IHasPrice { decimal PricePerUnit { get; } }
public static class TraitExtensions
{
public static decimal CalculateTotalPrice<T>(this T instance)
where T : class, IHasPrice, IHasQuantity
{
return (decimal)instance.Quantity * instance.PricePerQuantity;
}
}
In my opinion, abstract classes and class inheritance is overused.
SOLID design principles teach us that Liskov's substitution principle implies that class inheritance should only be used if the inherited class is substitutable for the ancestor. This means that all methods should be implemented (no throw new NotImplementedExeption()) and should behave as expected.
I personally have found class inheritance useful in the case of the Template Method pattern as well as for state machines. Design patterns such as the builder pattern are in most cases more useful than deep chains of inheritance.
Now back to your question; interfaces should be used most if not all of the time. Class inheritance should be used internally and only externally for purposes of definition, whereafter an interface should be used for interaction and the concrete implementation provided via a factory or to be injected via an IOC container.
Ideally when using external libraries, an interface should be created and an adapter implemented to expose only the functionality required. Most of these components allow to be configured beforehand or at runtime to be resolved via an IOC container.
In terms of decoupling, it is important to decouple the application from its implementations (especially external dependencies) to minimize the reasons to change.
I hope that my explanation points you in the right direction. Remember that it's preferred to refactor working implementations and thereafter interfaces are defined to expose functionality.
I'm not going to discuss what are the pros/cons of these two constructs in general, as there are enough resources on that.
However, In terms of 'decoupling' a component from another, interface inheritance is much better than abstract classes, or class inheritance in general (In fact I don't think being abstract or not does not make much difference in terms of decoupling as all abstract does is prevent the class being instantiated without a concrete implementation).
Reason for above argument is, interfaces allow you to narrow down the exposure to absolute minimum of what required by the 'dependent component', if it requires a single method interface can easily do that, or even be a marker interface without any method. This might be difficult with a base class (abstract or concrete) as it should implement all the 'common' functionality for that base. Because of this a component dependent on the 'base type' will automatically 'see' all the common functionality even it does not need them for it's purposes.
Interfaces also gives you the best flexibility as even classes inheriting from bases which have nothing in common, can still implement an interface, and be used by the component expecting that interface. Good example of this is IDisposable interface.
So, my conclusion is for decoupling concern have all your components depend on interfaces than base types, and if you find most of your classes implementing that interface has a common implementation then have a base class implementing that interface and inherit other classes from that base.
The core difference is this:
Interfaces expose zero or more method signatures which all descendants must in turn implement (otherwise code won't even compile).
Interface-exposed methods can either be implemented implicitly (every type derived from the interface has access to them) or explicitely (methods can be accessed only if you typecast the object to the interface type itself). More details and an example can be found in this question.
Abstract classes expose zero or more full-fledged methods, which descendants can either use or override, providing their own implementation. This approach allows you to define a customizable, "default" behavior. Abstract classes allows you to easily add new methods with no issues (NotImplementedException really shines when adding methods to abstract classes), whereas adding a method to an interface requires you to modify all the classes implementing it.
The final point is, that a class can implement more than one interface simultaneously.
Some real-world example might be:
A hard drive which provides both USB and LAN ports is a good demonstration of multiple interface inheritance
A Laptop which has a LED marked "bluetooth" but no bluetooth hardware on board is a good analogy of the concept of not implementing an abstract method (you have the LED, you have the little B symbol, but there's nothing under the roof).
Edit 1
Here's a MSDN link explaining how to choose between interface and classes.
Defining a contract using an abstract class means that your implementers must inherit from this abstract class. Since C# doesn't support multiple inheritance, these implementers will not be able to have an alternate class hierarchy, which can be pretty limiting for some. In other words, an abstract class basically otherwise robs the implementer of the class hierarchy feature, which is often needed to get or use some other capabilities (of a framework or class library).
Defining a contract using an interface leaves the class hierarchy free for your implementers to use any way they see fit, in other words, providing much more freedom of implementation.
From a perspective of evaluation criteria, when we talk about coupling here we can speak to concerns of three separable authors, the client using (calling) the API/contract, the definer of the API/contract, and the implementer of the API/contract; we can speak to freedom (the fewer restrictions, the better), encapsulation (the less awareness necessary, the better), and resilience in the face of change.
I would offer that an interface results in looser coupling than an abstract class, in particular, between the definer and the implementer, due to higher freedom offered the implementer.
On the other hand, when it comes to versioning, you can at least add another method to the abstract class without necessarily requiring updates to subclass implementations, provided the added method has an implementation in the abstract class. Versioning interfaces across DLL boundaries usually means adding another interface, much more complex to roll out. (Of course, this is not a concern if you can refactor all the implementations together (say, because they're all in the same DLL)).
The best way to understand and remember difference between interface and abstract class, it's to remember that abstract class is a normal class and you can do everything with abstract class that you can do with the normal class with two exceptions.
You can't instantiate an abstract class
You can have abstract method only in abstract class
Coding to interface provides reusability and polymorphism.As far as class implements interface,the interface or abstract class can be passed to parameter instead of class that implements the interface.Urs common technical problem is handled vis designing interface and abstract class and implementing it and giving subclass the specific functionality implementation.Imagine its like framework.Framework define interface and abstract class and implement it that is common to all.And those that are abstract is implemented by client according to its own requirement.
public interface Polymorphism{
void run();
Void Bark();
Energy getEnergy(Polymorphism test);
Public abstract class EnergySynthesis implements Polymorphism{
abstract void Energy();
Void Bark(){
getEnergy(){
}
void run(){
getEnergy();
}public EnegyGeneartion extends EnergySynthesis {
Energy getEnergy(Polymorphism test){
return new Energy( test);
}
MainClass{
EnegyGeneartion test=new EnegyGeneartion ();
test.getEnergy(test);
test.Bark()
.
.
.
.
.
//here in Energy getEnergy(Polymorphism test) any class can be passed as parameter that implemets interface

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.

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