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.
Related
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.
In c sharp abstract methods must be implemented by child class. So my question is when an interface inherits another interface why doesn't it implement all of base interface members.
public interface IShape
{
void Points();
}
public interface ICircle: IShape
{
void IsDrawAble();
}
When i run this program in Visual Studio 2010 and no error came up. By definition ICircle must implement Points function.
Thanks
Interfaces don't implement anything.
An interface simply contains a list of members that concrete classes need to implement.
There would be no point in re-declaring members that were already required by a base interface.
Similarly, an abstract class that inherits another abstract class (or interface) does not need to implement any of its methods.
When you implement ICircle you'll need to implement Points() as well. The following code does not compile:
class MyClass : ICircle
{
void IsDrawAble() { }
}
So what you stated should be : "By definition all implementations of ICircle must implement the IShape members as well"
You answered the question yourself. Because it's an interface. Interfaces are not classes, therefore they don't have to (in fact cannot) implement other interfaces they inherit.
When you create this kind of hierarchy between interfaces, you are defining who implement the Circle interface will also implement IShape. So, for sample:
public class Test : ICircle
{
public void Points()
{
// some code
}
public void IsDrawAble()
{
// some code
}
}
Using it:
ICircle obj = new Test();
obj.Points();
obj.IsDrawAble();
or
IShape obj = new Test();
obj.Points();
An interface represents a contract. They contain only the signatures of methods, properties, events or indexers. An interface doesn't implement at all. A class/struct that implements an interface must implement the members of the interface that are specified in the interface definition.
The hierarchy you have created simply means that whatever implements the ICircle interface also implements the IShape interface.
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.
I have a few questions regarding interfaces.
Why we can't use virtual keyword with Interfaces members
Why we can't use override keyword in derived class from interfaces
Suppose
interface Iface
{
void Func();
}
class Program : Iface
{
static void Main(string[] args)
{
}
public void Func()
{
Console.WriteLine("In func");
}
}
Why I need to use public on member functions in derived class from interface i.e. in Func() definition? If I am not using public keyword it will result in a compile time error
Can we use static Members in Interface?
Marking a method virtual gives the inheriting class the option to override the respective method. But when inheriting from an interface the implementation is not optional but mandatory. Every interface method is abstract by definition.
You don't override the methods, you implement them. An interface method has no own implementation, there is nothing to override. It just wouldn't make any sense.
Why a C# interface method implemented in a class must be public
No we can't use static methods on an interface
Interfaces don't need that. The implementation can be virtual.
An implementation doesn't need that - there is nothing to override.
You will have to instantiate a Program to call Func. Also there is no concept of static interfaces.
Interfaces dont act like class because, we cant make an object of interfaces if we can make make an object of interfaces to achieve multiple inheritance then we can face diamond problem that occur in the case of multiple inheritance of classes.
If I have a project that contains similar classes and some may use the same implementation, but in most cases they implement their own way of handling the methods defined in an interface or abstract class. I am trying to figure out if an interface/abstract class is better or not. I don't get the point of an interface if you can just use an abstract class with virtual abstract methods.
Here is an interface:
public interface IAthlete
{
void Run();
}
Here is an abstract class:
public abstract class Athlete
{
public abstract void Run();
}
Here is an implementation of the interface:
public class Sprinter : IAthlete
{
public void Run()
{
Console.WriteLine("Running Fast....");
}
}
Here is an extension of the abstract class:
public class MarathonRunner : Athlete
{
public override void Run()
{
Console.Write("Jogging....");
}
}
Now if I decide to add a method called Stop to either the interface or abstract method, Sprinter and MarathonRunner both break and because I can provide some default implementation to abstract, it seems like a better choice. Am I missing something?
There are 2 main differences between Interfaces and abstract super-classes:
Abstract Classes
code reuse is possible by using an abstract super-class
you can only inherit one super-class
Interfaces
every method has to be implemented in each sub-class
a class can inherit more than 1 interface (multiple inheritance)
In the case where all you have is one piece of commonality to extract, you're quite right that there isn't a substantive difference between the two. But this is rather like saying "in the case of adding 1 to 2, there's no difference between an int and a double" - it's technically true, but not a particularly useful guide to how to think.
In case with any more complexity than this (that is, in most cases) there will be more classes, and pieces of common baheaviour to extract. Then you have to start making a significant choice between class inheritance and interface implementation, taking into account things like:
you only get one shot at choosing a base class, but you can implement as many interfaces as you like
if you want your 'parent' to do any work, it needs to be a class not an interface
and so on.
In general, the semantics of your classes should guide you - where the 'things' have an "IS A" relationship (like MarathonRunner to Athlete), inheritance is suggested; where the 'things' have an "I CAN FULFIL THE CONTRACT OF A" (like, say, Person to Runner), interface implementation is suggested.
Interfaces are a btter way to go as the current consensus amongst the .NET developer comunity is that you should favour composition over inheritance, so Interfaces are a much better strategy (think of Injection Containers and how usefull they are as well, and lets not get started on unit testing).
also, classes can implement many interfaces but can only inherit from one class (abstract or otherwise). also structs can implement interfaces but not inherit from another class.
At the runtime level, interfaces are more efficient as the runtime doesnt have to walk the inheritance stack in order to work out the polymorphic implications of calling a specific member.
Interfaces are a very useful feature, and are very similar to abstract classes, and in some circumstances, exchangable with abstract classes.
But, don't jump straight to interfaces, unleass you have to (very common antipattern in Java developers). I suggest, by reading your example, to stick to abstract classes.
Most of the times I only use interfaces, when I have several non related classes, and I need them to have common members, as If these classes came from the same base class.
In your example, you are trying to find what happen if you need a new stop method, when adding a base virtual method. These can be solved in a different approach, that is not Abstract Classes versus interfaces.
There are 3 choices:
(1) Add an abstract method that coerce the programmer to override it, in order to instantiate objects.
(2) Add a new virtual method that does something, but doesn't have to be overriden.
(3) Add a new method that does nothing, maybe applies to your case.
// cannot instantiate an abstract class
public abstract class Athlete
{
// helper method:
public /* non-abstract */ void DoNothing()
{
// does nothing on purpouse !!!
}
// (1) virtual & abstract method, must be overriden
public abstract void Run();
// (2) new virtual method, doesn't need to be overriden,
// but, maybe you dont like what it does
public virtual void Stop()
{
Message.Show("Stop !!!");
}
// (3) new virtual method, doesn't need to be overriden,
// its safe to be called
public virtual void TakeBreak()
{
// works like an abstract virtual method, but, you don't need to override
DoNothing();
}
} // class Athlete
// in a non abstract class, you must override all abstract methods
public /* non-abstract */ class Runner: Athlete
{
public override void Run()
{
DoNothing();
}
public override void Stop()
{
DoNothing();
}
// don't need to override this method
// public virtual void TakeBreak();
} // class Trekker
// ...
Runner ARunner = new Runner();
ARunner.Run();
ARunner.Stop();
ARunner.TakeBreak();
The third kind of virtual method, that may apply to your example, doesnt' have a special name, I already post a question about it on stackoverflow, but, nobody knew an special name for this case.
Cheers.
An important difference between interfaces and abstract classes is how their members handle multi-generational inheritance. Suppose there's an abstract class BaseFoo with abstract method Bar and interface IFoo with method Boz; class Foo inherits BaseFoo and implements IFoo, and class DerivedFoo inherits from Foo.
If DerivedFoo needs to override BaseFoo.Bar, it may do so, and its override may call base.Bar() if it needs to use its parent's implementation. If Foo implements Boz implicitly using a virtual method, then DerivedFoo may override that method and call base.Boz() (the override being a function of the class rather than the interface) but if Foo explicitly implements IFoo.Boz, then the only way for DerivedFoo to change the behavior of IFoo.Boz will be to re-implement it. If it does so, then Foo's implementation of IFoo.Boz will become inaccessible, even within DerivedFoo's implementation of the same interface member.