Are interfaces in C# inherited or Implemented - c#

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

Related

Why use interface and abstract over just abstract?

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.

Can an interface be a descendant?

I was wondering: can an interface inherit from another class?
I'm trying to let an interface inherit from the MarshalByRefObject.
My intent is that all classes implementing the interface also inherit from that class.
No, it cannot.
An interface can only specify other interfaces that must be implemented. This is done by using the same syntax as inheritance, but it's something different.
You could use an abstract class instead that inherits from MarshalByRefObject and and requires your interfaces to be implemented.
Depending on how you need to enforce your requirement, generic constraints might help, too. For generic type parameters, you can set class constraints, like class Argh<T> where T : MarshalByRefObject, ISomeInterface.
An interface cannot inherit from a class. In order to do that C# would need to support multiple inheritance of implementation which is currently not supported.
Imagine if you could derive an interface, IMyInterface, from a class, MyClass. Then when you come to declare another class that implements that interface, you would have to write something like:
public class MyImplementingClass: MyBaseClass, IMyInterface
But that implies multiple inheritance of implementation since you are inheriting from both MyBaseClass and MyClass.
No, but an interface can inherit from another interface.
No, an interface cannot have any implementation, so it can't inherit from a class. However you can make an abstract class that inherits from MarshalByRefObject.
No. Classes can implement interfaces. Its not the other way round.
Class can inherit class and implement interface.
Interface can implement only interface but can neither inherit nor implement classes.

What is different between an abstract and an Interface class in C#?

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.

Class vs. Interface

I have a quite basic question:
When should we decide to use Interface or Class for a specific class?
For example: says we have 2 classes, Customer and Doctor.
In Inheritance (class): we could set these 2 classes to inherit from parent class Person.
Couldn't we do the same with Interface? Says we have InterfacePerson and have both Customer and Doctor implement the interface?
Thus, this lead to: when do we decide to use one over the other and vice versa?
Read the wikipedia article
Read a book, then read the chapters about OOP again
In your example, Person should be a class, because it contains implementation details that are common to both a Doctor and a Customer.
interfaces don't have (and don't need) implementation details - they only denote what objects which implement them are doing. Not how. Why is this useful? Because when you are using the object you don't care how it's going to do its job.
Let's take a look at a simple example - there is an interfaces Comparable (in Java at least). It denotes that its implementors can be compared with each other. So you can have two classes:
class Doctor implements Comparable {..}
class Customer implements Comparable {..}
Now you can have a common method which takes any set of objects which implement Comparable and call comparable1.compareTo(comparable2), because you know they can perform comparison - it's denoted by their interface.
Interface - describe the behavior
Class - do the behavior
A class extending another class inherits the behavior. On the other hand, implementing an interface just says it need to behave that way but the class still has to know the how-to.
Besides single inheritance limitations, code using interfaces are easier to refactor and test, e.g. provide a mock implementation for a database access object in unit tests.
So, the real answer is, it depends on your design.
It may be that you use interfaces to describe behavior, and abstract parent classes to implement the behavior that can be inherited by subclasses. Or maybe the subclasses are so different that each implements the interface in their own way.
Interfaces are used to enforce certain Methods/Properties. In a nutshell- an interface is a set of rules.
A class can be used to inherit/override base functionality.
Have a look at
Difference between class and
interface in C#?
C#: Interface vs. Class
Abstract Class versus Interface
interface (C# Reference)
In object modeling, one shouldn't use inheritance for people and their roles. One should instead model them with two associated objects. That is, using composition instead of inheritance.
So in a way, of three alternatives, your discussing the two wrong ones: inheritance and interfaces for modeling parties and roles.
A class is a template for a set of objects. Those objects have behavior, (and typically) state and characteristics. In regards to behavior, each object has an (implicit) interface already: the set of methods that can be externally called on it.
The question then becomes, why should you create a named interface, a subset of the interface already provided by an object?
One wants to represent a subset of behavior so different classes of objects can be treated polymorphically.
One wants to constrain the possible behavior of an object exposed to another, to a subset of its (implicit) interface because the object is acting in a different context.
Parent Class is the one which will have bare minimum properties common to all of its sub classes.
But Interface is a contract which tells its implantations to provide if it is not an abstract class.
And the One important difference between a class and interface is that
class inheritance will give relation between two common subclasses.
Where as Interface implementation gives a relation between two uncommon classes.
First thing to remember, Classes can be instantiated, Interfaces cannot.
Secondly, a Class can only extend ONE Class. Interfaces are not limited by this and so we can have multiple inheritance like so
public class foo extends Person implements Man, Mammal
foo is a Person. It is also a Man and a Mammal;
The only issue is Interfaces cannot have variables or method implementations where as a class(or abstract class for that matter) can.
Generally I would say stick with interfaces and avoid abstract classes if you can.
Simply put, you use classes when there is code/implementation involved and interfaces when it is just interface descriptions. When referring to objects in your code, prefer to refer to the interfaces as it makes it easier to replace the actual implementation (or add more and different implementations).
And yes, both Docor and Customer/Patient are likely to implement or extend Person.
Think of the interface as a contract. The class may commit to the contract (implement the interface)
Suppose you have class Person with subclasses Doctor and Patient. Then you'd have interface Treatable with the method getSymptoms() implemented by Patient and interface Treating with method cure(Treatable) implemented by Doctor. Most likely cure(Treatable) would call getSymptoms() at some point ...
In C#, multiple inheritance can be achived through Interface only.
Based on u r business requirement if there is a need that your class needs multiple inheritance going fwd, then use Interface else use class.
Also all members of Interfaces should be given defination in class i.e. interface members are must-implemented members.
class suggests that object that inherits base class is some kind of this class
if you use interface it only shows that your class have some common behaviour that interface describes

Abstract classes vs Interfaces

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).

Categories