Related
I'm reading some code online where someone implemented the following classes: IMapObj which is a normal interface, AbstractMapObj that derives from that interface and a lot of map objects that derive from AbstrsctMapObj.
Throughout all his code, he refers to IMapObj and not AbstractMapObj.
What's the benefit of using an interface and an abstract class instead of just an abstract class? Needless to say no other class derives from IMapObj, only AbstractMapObj.
There is only 1 reason to use both, and that is that the abstract class can provide a default implementation of some or all of the functionality. The interface can be easily mocked for testing.
What's the benefit of using an interface and an abstract class instead of just an abstract class?
In the example posted, there appears to be no real reason to use an abstract class. In other scenarios, the abstract class could provide a common base to a subset of the interface implementations. With the interface providing a more stable/common abstraction for the rest of the application/library.
Generally I would only use an abstract class to share a common implementation, not as an interface definition - but that's just my preference. There are many different styles and patterns that people use.
I know and read about abstract class and interface but one point I never understood is that, what is the use of class which cannot be instantiated.
I can use normal class and virtual method instead of abstract class?
what will happen when I instantiate base class?
You typically use an abstract class when you have some set of common functionality to be shared between derived classes. That is, you cannot use an interface because you want to provide some default functionality.
Take a look at the System.IO.Stream class. This class provides some common base functionality, but requires that specific types of streams implement some members in order for it to function. These members are also tagged abstract, which indicates to the compiler and runtime that there is no suitable base-class implementation. A non-abstract class that derives an abstract class must override all inherited abstract members, just like a class that implements an interface must implement all members defined on the interface.
In the stream example, the Read() method is abstract, but the ReadByte() method is not -- because ReadByte() can be implemented in terms of a call to Read(). (Although not optimally, which is why ReadByte() is virtual, so that a more efficient implementation can optionally be provided.) Virtual members are different, because they do have an implementation, but can optionally be overridden. Abstract members have no implementation by default, and must be overridden.
In other words, methods on an abstract class can use other abstract members on the class, even though they have no implementation! This is because a derived non-abstract class is required to provide an implementation -- an implementation is guaranteed to exist at the point that the method is invoked. This is analogous to how you can use members of an interface even though the members have no implementation on the interface, because it's guaranteed that an object implementing the interface must implement all of its members.
Subclasses like MemoryStream and FileStream override all of the abstract methods to form a concrete class, and they can be instantiated. However, you are able to store them in a Stream reference variable and treat them like a generic "black box" stream. This allows you to declare a method that accepts a Stream object, and you don't have to care what kind of stream it actually is.
Stream foo = new Stream(); // Invalid, Stream is abstract.
Stream foo = new MemoryStream(); // Valid.
So, now to summarize the answers to the questions you posed in your title. An abstract class cannot be instantiated because it may contain members that are abstract and have no implementation. The use of an abstract class is twofold: first, to be subclassed and allow the subclasses to share a common implementation of some members, and second, to allow instances of any objects of subclasses to be used through references to the abstract class.
Abstract classes are very useful and it's all about design. If, for example, you have an abstract base class called Shape, which has functions such as 'Draw' and 'Move'. You then inherit the Shape class to create a 'Circle' class and 'Square' class.
The inherited classes both have the functions Draw and Move. Move may have functionality in the base class which the child classes use, but draw functionality is handled by each child.
While you then instantiate a Circle and Square, it is meaningless to have just a 'Shape' object.
Hope that helps.
Abstract and interfaces enable you to share some common logic but you can't instantiate, directlym any of them
To add to cdhowie answer the most relevant differences between interfaces and abstract classes are:
Inheriting from an abstract class forces child classes to be compromised with a chain of hierarchy. With interface different classes implementing it are completely loose from each other.
With abstract classes you can have methods or properties with logic, that is, some code is implemented itself in the abstract class. In interface there is no code or logic thus forcing implementors to write all the logic
Abstract class and interface class are language features both offering some compile time rules and some run time rules aiding design. So far instantiating abstract class or interface class goes, its not possible using the compiler for sure, if one were to program using assembly language for C++ or say intermediate language code/byte code for C# or Java it might be possible to instantiate them as well, I am not sure on this point though. Since at run time there is a type object for both abstract class and interface class.
I have a simple question in C#
Are Interfaces inherited or are they implemented?
Thanks
Classes implement interfaces. Abstract classes are being inherited. A class can inherit from one class, but implement as many interfaces as you want it to.
However, interfaces can also "inherit" other interfaces. They don't really implement them, so it's more like inheriting their interface contracts, but they can implement multiple interfaces, so it's not really inheritance either. A class that will implement an interface which inherits from other interfaces, will have to implement all interface contracts that are included in the original interface, and it's base interfaces as well, recursively.
You should also read about abstract classes, for more useful information on the general subject.
That's just terminology. According to one MSDN page and another one a class or struct implements an interface. However, when you declare a new interface, that interface may inherit from other base interfaces.
that depends if the thing 'using' the interface is a class or another interface.
A class implements the interface (and any interfaces that it inherits).
Another interface inherits (or extends) an interface
You implement an interface by using a class. It is implemented, because it has no definition. Once you have a class. Be it abstract or a normal class, you inherit, because you are inheriting pre-built functionality.
Although there is 2 caveats.
abstract classes don't have to add any implementation to their methods (throwing exceptions is acceptable, or even leaving them empty, or marking the methods and properties as abstract to show the implementation is incomplete. Empty implementations are legitimate as long as the return type is satisfied. They just have to define the methods used by the interface.
you inherit from other classes, but adding 'sealed' to the class name will stop any one else from inheriting it e.g. System.String and System.Type
Classes can implement one / more interfaces implicitly and/or
explicitly.
An interface can inherit other interfaces.
The implicit implemented methods of an Interface can be abstract / virtual can be
overriden in derived classes.
In short Interfaces are implemented and implementation of the interfaces can be inherited
What is different between an abstract and an Interface class in C#?
An interface is not a class, it is just a contract that defines the public members that a class must implement.
An abstract class is just a class from which you cannot create an instance. Normally you would use it to define a base class that defines some virtual methods for derived classes to implement.
Rather than writing whole thing here..
try http://www.codeproject.com/KB/cs/abstractsvsinterfaces.aspx
A class can implement multiple interfaces but can only inherit from one abstract class.
An abstract class can provide implementation for it's methods. An interface cannot provide implementations.
the level of interface is higher than abstract.
when u're design the strcuture, draw the uml, u should use interface.
when u're implement, then u should use abstract to extract repeat things.
anyway, the different is not only a syntax problem..
hope it helps.
Google "abstract class vs interface" and you'll get lots of explanatory articles...
A class can implement multiple
interfaces but can only inherit from
one abstract class.
Also, abstract classes may have some functions defined but interfaces will not have any function definition and the deriving class must define all of them.
I would explain this through the usage. Abstract class can be used when there is only one hierarchy, additionally without default implementation; while interface can be used across hierarchies (horizontally), often referred to as a behavior.
Interface is also an abstraction and in c# substitutes multiple class inheritance, so this may be confusing, but you have to distinguish when to use what.
Hope this helps,
Robert
The purpose of an abstract class is to provide a base class definition for how a set of derived classes will work and then allow the programmers to fill the implementation in the derived classes.
When we create an interface, we are basically creating a set of methods without any implementation that must be overridden by the implemented classes. The advantage is that it provides a way for a class to be a part of two classes: one from inheritance hierarchy and one from the interface.
I'm a bit confused about the usage of Abstract classes in C#. In C++, it makes sense to define a template which classes inheriting the abstract class can follow. But, in C# doesn't Interface serve the same purpose?
True that abstract classes can have default implementation which is not provided by Interfaces. So if implementation doesn't need to be included in base class, is it better to go for Interfaces?
I still like to provide a default abstract implementation of an interface, assuming it's a substantial interface (and it makes sense). You never know when you might add something to the interface that has an easy default implementation that could be included and given "for free" to anyone who inherits from the abstract base class.
This CodeProject article has a lot of information on the difference between the two including a table comparing and contrasting the features of each.
Interfaces define the contract between classes - the ways classes call each other. A class can implement multiple interfaces, but can only inherit from one abstract class.
True that abstract classes can have default implementation which is not provided by Interfaces. So if implementation doesn't need to be included in base class, is it better to go for Interfaces?
Yes :). If it makes sense to implement some methods in the base class which will be common to all inhereted class you should use an abstract class. If the base class would only be used to define an interface but there is no common logic between the inherited classes, use an interface.
Interfaces and abstract classes serve different goals. Interfaces are used to declare contracts for classes while abstract classes are used to share a common implementation.
If you only use abstract classes, your classes cannot inherit from other classes because C# does not support multiple inheritance. If you only use interfaces, your classes cannot share common code.
public interface IFoo
{
void Bar();
}
public abstract class FooBase : IFoo
{
public abstract void Bar()
{
// Do some stuff usually required for IFoo.
}
}
Now we can use the interface and base implementation in various situations.
public class FooOne : FooBase
{
public override void Bar()
{
base.Bar(); // Use base implementation.
// Do specialized stuff.
}
}
public class FooTwo : FooBase
{
public override void Bar()
{
// Do other specialized stuff.
base.Bar(); // Use base implementation.
// Do more specialized stuff.
}
}
// This class cannot use the base implementation from FooBase because
// of inheriting from OtherClass but it can still implement IFoo.
public class FooThree : OtherClass, IFoo
{
public virtual void Bar()
{
// Do stuff.
}
}
For your first question, Yes.
For your second answer i'll give you some tips I've followed.
Use abstract classes and interfaces in combination to optimize your design trade-offs.
Use an abstract class
When creating a class library which will be widely distributed or reused—especially to clients, use an abstract class in preference to an interface; because, it simplifies versioning.
Use an abstract class to define a common base class for a family of types.
Use an abstract class to provide default behavior.
Subclass only a base class in a hierarchy to which the class logically belongs.
Use an interface
When creating a standalone project which can be changed at will, use an interface in preference to an abstract class; because, it offers more design flexibility.
Use interfaces to introduce polymorphic behavior without subclassing and to model multiple inheritance—allowing a specific type to support numerous behaviors.
Use an interface to design a polymorphic hierarchy for value types.
Use an interface when an immutable contract is really intended.
A well-designed interface defines a very specific range of functionality. Split up interfaces that contain unrelated functionality.
You can implement any number of Interfaces, but can only inherit one Class. So Classes and Interfaces are quite different beasts in C# and you cannot use them interchangeably. In C# abstract classes are still classes, not interfaces.
If you don't have any default/common code, then go with an interface.
An abstract class can also serve as a template, where it defines the steps of some algorithm and the order in which they are called, and derived classes provide the implementation of these steps:
public abstract class Processor
{
// this is the only public method
// implements the order of the separate steps
public void Process()
{
Step1();
Step2();
//...
}
// implementation is provided by derived classes
protected abstract void Step1();
protected abstract void Step2();
}
Whilst it's true that an abstract class with no implementation is equivalent to an interface, interfaces and abstract classes are used for different things.
Interfaces can be used for polymorphism in the most general sense. For example, ICollection is used to define the interface for all collections (there are quite a few). Here it is defining the operations that you want to perform on a certain kind of type. There are many other uses (such as testability, dependency injection etc). Also, interfaces can be mixed and this works both conceptually and technically.
Abstract classes are more to do with templateable behaviour, where virtual methods are a place to 'fill in the gaps'. Obviously you can't mix abstract classes (at least, not in C#).
In C# a large deterrent for the use of abstract classes is that you can only use one. With interfaces you have the advantage of not limiting the base class for the implementation. To this end, I always use an interface even if I create an abstract base class to aid with the implementation.
Often another annoyance of base abstract classes is that they tend to rely on template arguments. This can make it very difficult for the rest of your code to utilize. The easy answer for this is to provide an interface to talk to the abstract class without knowing the type argument of the template class.
Others seem to be typing their answer faster, but allow me to summarize...
Use an interface. If you need to share implementation, you can also create an abstract base class that provides common implementation details.
Note that with C#3, you can provide default behavior for interfaces through the use of extension methods. There are some limitations, though, and abstract classes still have their place.
The rule I follow when modeling is:
Classes(abstract included) and structs model entities.Interfaces model behavior.
Entities implementing an interface can be considered as exhibiting behaviors that the interface(contract) exposes.
This is hinted at in a few of the answers but not explicitly stated.
The fact that you can implement multiple interfaces and only inherit from one base class, as if they were two sides of the same coin, isn't a good way to look at it.
Don't think of interfaces as part of an object hierarchy. They are usually just small parts of functionality (or at least specific if not small) that your real object heirarchy can declare as implementing. Take IDisposable for instance. If you were the one writing that, would you ask yourself whether it should have been an abstract class or an interface? It seems obvious that in this case they are two completely different things. I want to BE disposable. Think ICloneable and IEnumerable. You can implement those in your class without having to try and make your class derive from some unrelated classes like List or Array. Or take IEnumerator. Simply gives a MoveNext type of view to an object. My class can provide that functionality without having to awkwardly be derived from some other sequential collection data type that has nothing to do with my class.
I always prefer interfaces as long as the base class don't have some really "heavy duty" implementation that will save lots of time to the implementers.
giving that .net allows only one base class inheritance, forcing your users to inherit is a huge limitation.
You should always prefer programming to interfaces than to concrete classes.
If you also want to have a default implementation you can still create a base class which implements your interface(s).