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
Related
What I have is a non generic interface for the purpose of having a common contact that I can call functions. The interface returns objects which implement other interfaces. For example:
public interface ISearchAdvancedInputController
{
ISearchAdvancedInput GetAdvancedInput();
void LoadFromModel(ISearchAdvancedInput advancedInput);
}
I then currently have an abstract generic class which implements the interface but imposes requirements of the type. The types of the abstract class must implement the same interfaces as the interface's properties and functions demand. I cast the generic type to the implemented type when necessary so that I can satisfy the requirements of the implemented non abstract interface. This way, I can extend this abstract class and it will enforce type requirements across a larger class w/ many different types used across it. For example:
public abstract class ISearchAdvancedInputControllerBase<standardInput, advancedInputType> : ISearchAdvancedInputController
where advancedInputType : ISearchAdvancedInput
{
protected abstract advancedInputType GetAdvancedInput();
ISearchAdvancedInput ISearchAdvancedInputController.GetAdvancedInput()
{
return GetAdvancedInput();
}
void ISearchAdvancedInputController.LoadFromModel(ISearchAdvancedInput advancedInput)
{
LoadFromModel((advancedInputType)advancedInput);
}
public abstract void LoadFromModel(advancedInputType advancedInput);
}
This works really well in general however it falls short because I'm having to use an abstract CLASS in order to perform this overriding. As such when I want to actually make use of it for more concrete examples, I encounter the error that I can only extend a single class.
So to get around this I extend the "other" class in the previous base abstract class. However this is not ideal because if I wind up creating another concrete implementation I need to redefine all of the type translations that I'm doing which is NOT related to the concrete classes implementation.
What I'd like is to not have an abstract class but instead some sort of abstract interface. If I had this I'd be able to implement concrete classes more succinctly. I've looked at other instances of this question and have tried what seems to be the main suggestion which is to make the initial interface generic and have the type extend the resulting interface type and then extend that interface with the more abstract interface as such:
interface TestGenericInterface<a> where a:TestClassInterfaceA
{
TestClassInterfaceA testGeneric { get; }
}
interface TestGenericComplexInterface<a> : TestGenericInterface<a>
where a:TestClassInterfaceA
{
new a testGeneric { get; }
}
However the concrete class seems to suffer from the same issue that's shown when you start from a non generic interface where each function / property of the base interface needs overwritten.
public class TestClass : TestGenericComplexInterface<TestGC>
{
public TestGC testGeneric => I want to complete this because its return is the type that I'm wanting to use for this concrete implementation
TestClassInterfaceA TestGenericInterface<TestGC>.testGeneric => I don't want to have to complete this because this function is already handled by the previous function in a round about sense.
}
public class TestGC : TestClassInterfaceA { }
I do see a note that I could provide default implementation of functions if I use c# v8.0 or greater, so I must be on a version prior to that but I figure this should be possible w/o that, but maybe in a different way. Hope ya'll can assist.
I think I have a very naive question here that I didn't knew before that it was even possible. Forgive me if my title question is a bit vague because I don't even know how to describe it. Here is the code that looks weird to me.
public interface IMyInterface
{
void ImplementMe();
}
public class StandAlone
{
public void ImplementMe()
{
Console.writeline("It works!");
}
}
public class SubClass : StandAlone, IMyInterface
{
// no need to implement IMyInterface here but it still work!!!
}
IMyInterface myInterface = new SubClass();
myInterface.ImplementMe(); // Output : "It works!"
I just want to know the following :
What is the right term to describe this approach?
What is the practical benefit of this kind of approach?
What kind of problem it tries to solve? or What scenario this will be applicable?
Well, first case that comes to my mind - when you don't own source code of StandAlone class, but later you decided to introduce interface which describes behavior of StandAlone class. E.g. for unit-testing (it's not best practice to mock code which you don't own, but sometimes it might be helpful) or you want to provide alternative implementation of StandAlone behavior in some cases. So either you have no options for unit-testing such code:
public class SUT
{
private readonly StandAlone dependency;
public SUT(StandAlone dependency)
{
this.dependency = dependency;
}
// ...
}
But if you'll introduce interface, you can actually switch to dependency from IMyInterface instead of StandAlone. And provide SubClass as implementation of interface with zero efforts.
public class SUT
{
private readonly IMyInterface dependency;
public SUT(IMyInterface dependency)
{
this.dependency = dependency;
}
// ...
}
But SubClass does implement the IMyInterface - it has all the required public members with the right signatures. There's no specific terminology since there's nothing weird about it.
In fact, some languages take this even further, and allow you to cast any object to an interface, as long as the class has the right members (and in yet more flexible languages, even if it doesn't).
The main benefit is again the same as any other way to use interfaces - it allows you to abstract the implementation away from the interface. It's just a shortcut to having to do an explicit interface implementation, something like:
class SubClass : BaseClass, IInterface
{
void IInterface.MyMethod()
{
base.MyMethod();
}
}
You might think that you could just implement the interface in the base class, but there's plenty of reasons why you wouldn't:
You don't want to maintain a public interface for the base class, it's just an internal class that shouldn't be exposed outside.
You don't have a way to change the base class to include the interface, so if you want to keep an inheritance chain, you must subclass and add the interface to the subclass.
The inferface contains some members that aren't contained in the BaseClass.
You'll probably find a couple more reasons if you try.
But the main point is: why not? You need a reason to do something (expand the definition of the base class instead of just the subclass). Adding abstraction everywhere along your codebase is rarely beneficial - you're trying to find a good trade-off between clarity of intent and clarity of implementation. An interface on a base class might help or hinder that.
One legitimate use of this pattern (Outside of simply the original programmer should have put the interface on the base class) could be that Standalone is in a 3rd party (or inaccessible) assembly, and IMyInterface was written in your own code to provide a Facade.
Consider this;
Your app wants to provide some functionality. You define an interface with method ImplementMe.
Standalone is in ThirdParty.dll and provides this exact method name (Perhaps you modelled your interface on that method name on purpose)
You subclass Standalone within your own code in order to implement your functionality.
Maybe you have a second way of implementing ImplementMe for which you have your onw class implementing your own interface. (public class MyOwnImplemetation : IMyInterface {... })
You could then use DI to instantiate the correct implementation of StandAlone or MyOwnImplemetation but treat them both as IMyInterface.
Not all classes are direct implementations of interfaces.
For example, let's put a good sample based on a simple class inheritance:
public class Person
{
public Guid Id { get; set; }
public string Name { get; set; }
public string LastName { get; set; }
}
public class Employee : Person
{
}
Now, let's imagine that we need to store uniquely-identifiable objects in some common store where we don't care about the entities' types but just about they're uniquely-identifiable.
BTW, we consider that persons shouldn't be stored within such store, because they're not valid entities within our organization but they're just there to improve code reusability and don't repeat ourselves.
So we define an interface like this:
public interface ICanBeUniquelyIdentifiable
{
Guid Id { get; set; }
}
...and we don't implement it on Person but we do so on Employee:
// Now an employee is an actual object that can be uniquely identifiable,
// and this isn't true because Person has an Id property, but because
// Employee fulfills the contract!
public class Employee : Person, ICanBeUniquelyIdentifiable
{
}
Background
I would say that your reasoning should be that you implement interfaces where they really matter to be implemented, and reusability shouldn't be the key point when implementing interfaces.
Actually, you should implement interfaces on objects which should be accepted on some API and you just need a subset of the full type of a given object.
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
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.
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.