Why do we need interfaces when abstract classes exist? [duplicate] - c#

This question already has answers here:
Why do both the abstract class and interface exist in C#?
(11 answers)
Closed 9 years ago.
One interviewer has asked me the below question and I couldn't answer:
Why do we need Interfaces when abstract classes exist?
Whatever the methods we are writing in interface those we can write in Abstract class also. Then why do we need interfaces separately?
Can anybody please tell what is the reason?
Advance thanks...

There are several differences,
Abstract classes can have only one parent class, whereas a class can implement several interfaces.
Interfaces cannot contain any implementation, abstract classes can (they can have abstract methods in addition to not abstract methods).
Interfaces are great to focus on a 'view' we can have on a class. This view can be shared by multiple classes implementing the interface.
For instance, DataTable implements IListSource and ISerializable. So, depending on the context, you can view it as a list source to read its data or as a class which instances can be serialized. When you do so, you focus on a specifc view you can have of an instance.

Interface represents a contract, while you can have several implementations of that contract in different (abstract) classes.
public interface IExample
{
void Do();
}
public abstract class DoFirst : IExample
{
public void Do()
{
Console.WriteLine("Doing it the first way");
}
}
public abstract class DoSecond : IExample
{
public void Do()
{
Console.WriteLine("Doing it the second way");
}
}
public class DoFirstConcrete : DoFirst, IExample
{
public void DoSomethingElse()
{
Do();
Console.WriteLine("Doing something else also with first.");
}
}
public class DoSecondConcrete : DoSecond, IExample
{
public void DoSomethingElse()
{
Do();
Console.WriteLine("Doing something else also with second.");
}
}

You abstract class is a partial implementation. Interfaces are contracts, to know what your abstract class can do. You need an interface to describe it.

You can implement multiple interfaces, but only inherit from one abstract class.
An interface is an empty shell, there are only the signatures (name / params / return type) of the methods. The methods do not contain anything. The interface can't do anything. It's just a pattern
Abstract classes, unlike interfaces, are classes. There are more expensive to use because there is a lookup to do when you inherit from them.
Abstract classes look a lot like interfaces, but they have something more : you can define a behavior for them. It's more about a guy saying "these classes should look like that, and they got that in common, so fill in the blanks!".
Quoted e-satis from here (much more information too):
What is the difference between an interface and abstract class?

You can't inherit from multiple abstract classes, but you can implement multiple interfaces.

Related

Different classes have to implement an interface method in exactly the same way

I have and interface defining a bunch of different properties and a State property that is a compact summary of all the other.
So I have a common interface named IStateful
interface IStateFul
{
string State { get; set; }
}
I have some classes implementing this interface in different ways - one asks for user input, another read the values from a service, one could get data from a DB.
But all of them have to compute the state in exactly the same way to be "compatible" with each other. So the implementation of State in the different classes have to use the other property in exactly the same way to compute the state string.
As of today I copy and paste the state implementing method from a class to the other. This is obviously the worst option.
Other options could be
Common abstract base class (I tried this and it's ankward, the abstract class have to implement abstractly all the interface method that it does not care at all, then the derived classes have to override them all)
Another class with a static method to be called (a "serializer" ???)
An extension method for the interface (just the same as option 2 but with different sintactic sugar)
There is a common pattern to follow? Or is there a basic design flaw that I'm missing to see?
In an abstract class you should only mark the methods that need to be overridden as abstract, otherwise mark them virtual:
public abstract class MyBase
{
protected virtual void DoSomething()
{
//My Implementation here
Console.WriteLine("Base implementation");
}
//Will give compile-time error if you don't override this in derived class
protected abstract void DoSomethingElse();
}
Then in your derived classes you can use either the base implementation of the virtual methods or override them and the abstract methods will need to be implemented:
public class Derived : MyBase
{
protected override void DoSomethingElse()
{
Console.WriteLine("Derived implementation");
}
}
public static void Main(String[] args)
{
var derived = new Derived();
derived.DoSomething(); //Base Implementation
derived.DoSomethingElse(); //Derived implementation
}
If using an interface is not absolutely required by your design, you can use an abstract class instead of the interface and not both at the same time. It will work practically the same way but allows you to define a method/property implementation.
Your case is a common pattern addressed by abstract classes.
I would define the interface IRequireState
public interface IRequireState
{
bool GetState();
}
And use that for all classes requiring state. There is a programming principle called "The Interface Segregation Principle" (ISP) which basically states that you should ONLY implement an interface in the classes where it makes sense to do so.
According to the Open Closed Principle you can always subtitute a derivative, so for example, if you have 3 classes, all implementing the IRequireState you can then type code like:
foreach(var job in myListOfJobs)
if(job.GetType() == typeof(IRequireState))
((IRequireState)job).GetState();
I hope that helps you on the path to good Object Oriented design. Make sure to read up on the SOLID principles. They help alot in these questions.
If you have some jobs that do the same GetState() thing, then it would make sense to have a base class which implements the same interface, but you're then free to ALSO have jobs with various, different GetState() implementations.

Why IDisposable is an Interface, not abstract class?

Can we define IDisposable as an abstract class instead of Interface like below. What are disadvantages?
public abstract class absDisposable
{
public abstract void Dispose();
}
public class childClass : absDisposable
{
SqlConnection objConnect = new SqlConnection("connstring");
public override void Dispose()
{
if (this.objConnect != null)
{
this.objConnect.Dispose();
this.objConnect = null;
}
}
}
I wrote that code in the same Interface works, else there is no reason of abstract class with no implementation. This is same way we define Interface, without any implementations.right? However, the question is not the IDisposable only, its about all Interfaces we use. Why don't we simply write the methods we require, why do we go one level more for Implementing Interfaces? Since Interface serves no purpose. We always have to give our own implementations in derived classes, so no question of code re-usability also. And how Interfaces resolve lack of multiple inheritance in c#, if we cannot re-use codes? All I want to know is what situation an Interface proves its presence?
Since C# does not support multiple inheritance, your idea would make it impossible to combine disposability with an existing base class.
Since IDisposable doesn't include any implementation, there is no reason to make it an abstract class.

Abstract method in oops [duplicate]

This question already has answers here:
abstract method use vs regular methods
(6 answers)
Closed 9 years ago.
Why we are using abstract method because if we have declared abstract class then we must implement that method in derived class that make 2times trouble then why we are not using simple method instead of abstract methods????
abstract class Animal
{
abstract public void Voice(); //
}
class Dog : Animal
{
public void Voice()
{
Console.WriteLine("bark!");
}
}
class Cat: Animal
{
public void Voice()
{
Console.WriteLine("meow!");
}
}
Look at abstract method Voice. What it should be if you imagine that it is abstract animal's voice?
By creating an abstract class which has many subclasses that fulfill the abstract behaviour and maintain the contract of the abstract superclass, you can write methods that are agnostic to the coding implementation of an object, just knowing it will do as told. The different subclasses could get data from different sources, be optimized for different things, have different side effects, etc
If you are learning about object oriented programming school class, then probably like me, none of the principles you learn will make sense - because in small programs, and to make programming examples easily digestable they MUST be small, OOP usually just adds baggage and boilerplate. But the larger your programs get, the more reusable, the more usable in different contexts they must be, the huger and grander and vaster the things they must do and do right, the more OOP techniques simplify the process of coding and thinking about code.
Abstract methods are only allowed to be declared in abstract classes, which means that the classes implementing the abstract class HAS to implement the abstract method, whereas any other method in the abstract class can be overridden, or used as is.
From abstract (C# Reference)
•Abstract method declarations are only permitted in abstract classes.
•Because an abstract method declaration provides no actual
implementation, there is no method body; the method declaration simply
ends with a semicolon and there are no curly braces ({ }) following
the signature. The implementation is provided by an overriding
method override (C# Reference), which is a member of a non-abstract
class.
abstract class A{
abstract void method1();
void method2(){
//implementation
}
}
class B extends A{
public void method1(){
// implementation
}
}
class C extends A{
public void method1(){
// implementation
}
}
Say B and C is two subclass of A. which have a common method method2 but a different method method1. So you can extend A in both classes. There common method will be inherited automatically. And there you can define your own behavior by implementing method1 in the subclasses.

"Base abstract generic class is a bad choice in most situations." Why? (Or Why not)

I have just seen on the comment to a blog post:
Base abstract generic class is a bad
choice in most situations
Is this true, if not why?
What insight(s) leads to this statement?
I agree, because anything that inherits an abstract generic class will not be polymorphic with the base class. That is, if you have
abstract class myBase<T>
then you create
class myThing: myBase<thing>
class myOtherThing: myBase<otherThing>
you can't create methods that work against myThing and myOtherThing since they do not share an ancestor. There's no point in the base class being abstract, really, it might as well just be a class.
But if you have a base class
abstract class myBase
class myBase<T>: myBase
as is a common pattern for generic classes (like IEnumerable - using interfaces), then they all share myBase.
(edit) I just read the actual blog post - and actually, the comment is not really valid in that situation. The "abstract generic base class" he's referring to, Range<T> inherits IEnumerable<T> which inherits non-generic interface IEnumerable. So it's not really an "abstract generic base class." But generally I think it's true.
"Most situations" is outrightly vague. A generic abstract class (or interface) is a bad idea if the only common ancestor between descendants of such class is System.Object (as noted by other commenters of this question).
Otherwise (as in, if you do have a meaningful common ancestor), it's a good idea if you want to "rename" or "specialize" members. Consider this example:
// Meaningful common ancestor for the working classes.
interface IWorker
{
object DoWork();
}
// Generic abstract base class for working classes implementations.
abstract WorkerImpl<TResult> : IWorker
{
public abstract TResult DoWork();
object IWorker.DoWork()
{
return DoWork(); // calls TResult DoWork();
}
}
// Concrete working class, specialized to deal with decimals.
class ComputationWorker : WorkerImpl<decimal>
{
override decimal DoWork()
{
decimal res;
// Do lengthy stuff...
return res;
}
}
In this example, DoWork() was redefined in the abstract class, becoming concrete and specialized in ComputationWorker.
One problem with abstract generic base class is that you can't type decorate :
public abstract class Activity<TEntity>
{
public Activity() { }
protected virtual object Implementation { ... }
}
public abstract class CompensableActivity<TEntity,TCompensation> : Activity<TEntity>
where TCompensation : Activity<T>, new()
{
public CompensableActivity() { }
protected override object Implementation
{
get { new Wrapper(base.Implementation, Compensation); }
}
private Activity<TEntity> Compensation
{
get
{
var compensation = new TCompensation();
if(compensation is CompensableActivity<TEntity,Activity<TEntity>)
{
// Activity<TEntity> "does not meet new() constraint" !
var compensable = comp as CompensableActivity<TEntity, Activity<TEntity>>;
var implement = compensable.Implementation as Wrapper;
return implement.NormalActivity;
}
else { return compensation; }
}
}
}
Kragen makes a good point. Anything that is less than 50% of your code is "the wrong choice in the majority of situations".
However, even though nowhere near 50% of your classes should be generic abstract base classes, it also isn't less of a good thing than any other language feature.
For example, BindingList<T> could be considered an abstract generic base class. It's a generic container, and sorting requires you to derive from it and override ApplySortCore.
KeyedCollection<TKey, TItem> doesn't just act like an abstract generic base class, it is one. To use it you MUST derive from it and implement GetKeyForItem.
I disagree with the crowd here. In some cases an abstract generic class is the best design.
A good example in .NET can be found in System.Collections.ObjectModel where the KeyedCollection allows you to override and implement a typed serializable dictionary collection easily!
I elided most of the code but this is the principle:
public class NameCollection : System.Collections.ObjectModel.KeyedCollection<string, INamedObj>
{
protected override string GetKeyForItem(INamedObj item)
{
return item.Name;
}
}
Well, statistically speaking if someone asked me "should I make this class an abstract generic class?", the answer would almost certainly be no - in 3 years of .Net development I think I can count the number of abstract classes that I've written that had generic type parameters on one hand.
Other than that I can't see any particular reason for an abstract generic class to be considered a Bad Thing - its just not that common.
There are situations where an abstract base class is useful thing.
We have several .net applications that use different database engines. Several sql server, a couple of mysql and a bunch of oracle apps.
We have a generic common database object which is based on an abstract class that is a factory that returns the proper database object in a factory setting based on the type of database.
That way if I am starting a new application, all I have to do is load this database object, pass in the type, pass in the connection string, and bam... i'm set...
I guess what I'm trying to say is it all depends on the context and how its actually used.

How to partially implement a contract in an abstract base class?

I have a interface as follows
public interface IX
{
void MethodA();
void MethodB();
}
I have two method contracts in the interface MethodA and MethodB. I will define set of classes that will implement the above interface. Out of these two methods MethodA is common for all the types that will implement the interface. I can define a abstract class as follows
public abstract class XBase:IX
{
public void MethodA()
{
// Common behaviour implementation
}
public abstract void MethodB();
}
And inherit this class to all the types that need to implement the above interface. It works.
But here in the abstract class i add 'public abstract void MethodB();'. It looks like repetition of the MethodB contract.
Why C# does not permit partial interface implementation if the class is abstract?. The above interface has only two methods. suppose one interface has 10 methods and 5 are common functionality and 5 are not, we are forced to add the 5 methods that are not common in the abstract class?
Because the C# language specification says so. Chapter 13.4.7:
Like a non-abstract class, an abstract class must provide implementations of all members of the interfaces that are listed in the base class list of the class.
Why the C# designers chose to specify the language like this is probably best answered by Eric Lippert. I'd personally guess at reducing the odds that unintended method hiding occurs, producing error messages that are very hard to interpret. I would personally have been more comfortable requiring the use of the overrides keyword for the interface method implementation. But they chose not to.
The reason it doesn't support this is because your superclass doesn't fulfil the contract. The only way for an abstract class to force implementation on its subclasses is to define abstract methods.
If you don't want the abstract class to have those abstract methods defined then you have to tell the subclasses to implement the interface instead.
Question would have to be, why would it be a problem having 5 abstract methods on your superclass?
Interfaces do pass along the contract requirement to each other, so as far as you have IFoo and IBar : IFoo, then classes inheriting from IBar must implement both interfaces, as clearly IBar cannot implement the members of IFoo itself. Why this behavior could not be extended to abstract base classes, I don't know. I'm sure there is a good reason, and since Hans posted the spec, it's obviously intentional.
As a please do not try this at home approach, you could do something like
class Derived : Base, IFoo
{
public void MethodB()
{
}
}
abstract class Base
{
public Base()
{
if (!(this is IFoo))
throw new InvalidOperationException("must implement IFoo");
}
public void MethodA() { }
}
interface IFoo
{
void MethodA();
void MethodB();
}
Which has the abstract base implement the methods it wants and then force the derived classes to implement the rest by enforcing that the derived classes implement the interface. The derived classes would then be responsible for implementing the methods that are not already in the base class. The problem with this approach is that this is a runtime requirement, not compile time.
How would you handle a situation where you have
interface IFoo {
void MethodA();
void MethodB();
}
abstract class Base: IFoo {
public void MethodA() {}
// MethodB gets implicitly generated
}
class Derived: Base {
public void MethodB() {}
}
Could you then do this:
Base myBase = ...
myBase.MethodB();
Ok you could, since MethodB is implicit. But what if you would later decide to remove the interface IFoo from the Base class? You just broke the Base's contract..Solution would be that generated methods would be explicit interface implementations, but that brings another kind of pain.
You can switch from 'abstract' to 'virtual' in the method declaration and provide an assertion:
public abstract void MethodB();
becomes
public virtual void MethodB()
{
Contract.Require( your condition );
}
I don't think abstract class or interface is doing any injustice in your scenario rather as per SOLID principles (specifically: Interface Segregation Principle) : https://msdn.microsoft.com/en-us/library/dn178470(v=pandp.30).aspx
It says large interfaces should be split into smaller and more specific ones so that client classes are not forced to implement methods they do not use at all. Utilizing this principle would solve your problem.

Categories