Why Interface support multiple inheritance and class doesnt in c# [duplicate] - c#

This question already has answers here:
Closed 12 years ago.
Possible Duplicates:
Why C# doen't support multiple inheritance
Should C# include multiple inheritance?
i like to what is reason for interface support multiple inheritance and class doesnt support

I would rather 'negate' your statement.. "interface support multiple inheritance".
Interface is NOT actually inheritance, it is JUST a "contract" of service/behavior that a class abides with.
By implementing an interface a class does NOT inherit anything per se.
And since a class/entity can bind with multiple contracts (behaviours), we can implement multiple interfaces in a class.

Because these are conceptually two totally different things.
If you inherit from a class, you inherit the code of the base class.
If you implement (not inherit!) an interface, you force your implementing class to have some predefined method/event/property signatures.
While multiple inheritance for classes is a notorious source of errors and confusion, having many interfaces in a class' inheritance list is about combining various behavioural aspects, and as such it is an important instrument for component-based programming.
Or, in other words: It is an implementation of the Favour Composition over Inheritance design principle.
Thomas

I'd be very interested in a more authoritative answer, but here's my take.
In languages that support multiple inheritance, the key ambiguity that is (arguably) unsatisfactorily resolved is what happens when you subclass from two types that both define a method with the same signature. For example:
public class BaseClass1
{
public string SomeMethod()
{
return "Implementation1";
}
}
public class BaseClass2
{
public string SomeMethod()
{
return "Implementation2";
}
}
public class MySuclass : BaseClass1, BaseClass2
{
}
Now what does the following return?
MySubclass mySubclass = new MySubclass();
string s = mySubclass.SomeMethod();
In C#, explicit interface implementation allows you to easily resolve this by definining both. After converting BaseClass1 and BaseClass2 to interfaces, we can have
public class MySuclass : IBaseClass1, IBaseClass2
{
string IBaseClass1.SomeMethod()
{
return "Implementation1";
}
string IBaseClass2.SomeMethod()
{
return "Implementation2";
}
}
The key of course being that there is no ambiguity with this syntax as it's not possible to access SomeMethod without first casting the target to either IBaseClass1 or IBaseClass2.

Related

C#: Should a base interface be included in the list of interface for a class implementation? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
C#: Interfaces - Implicit and Explicit implementation
Would someone explain the differences between these two beasts and how to use them. AFAIK, many pre.2.0 classes were implemented without generic types, thus causing latter version to implement both flavors of interfaces. Is the the only case why one would need to use them?
Can you also explain in depth how to use them.?
Thanks
There is a good and pretty detailed blog post about this.
Basically with implicit interface implementation you access the interface methods and properties as if they were part of the class. With explicit interface implementations you can only access them when treating it as that interface.
In terms of when you would use one over the other, sometimes you have to use explicit interface implementation as you either have a property/method with same signature as the interface or you want to implement two interfaces with the same signatures and have different implementations for those properties/methods that match.
The below rules are from Brad Abrams design guidelines blog.
Do not use explicit members as a security boundary. They can be called by any client who cast an instance to the interface.
Do use explicit members to hide implementation details
Do use explicit members to approximate private interface implementations.
Do expose an alternative way to access any explicitly implemented members that subclasses are allowed to override. Use the same method name unless a conflict would arise.
It's also mentioned in the comments in Brad's blog that there is boxing involved when using explicit implementation on value types so be aware of the performance cost.
In layman's terms, if a class inherits from 2 or more interfaces and if the interfaces happen to have the same method names, the class doesn't know which interface method is being implemented if you use implicit interface implementation. This is one of the scenarios when you would explicitly implement an interface.
Implicit Interface Implementtation
public class MyClass : InterfaceOne, InterfaceTwo
{
public void InterfaceMethod()
{
Console.WriteLine("Which interface method is this?");
}
}
interface InterfaceOne
{
void InterfaceMethod();
}
interface InterfaceTwo
{
void InterfaceMethod();
}
Explicit Interface Implementation
public class MyClass : InterfaceOne, InterfaceTwo
{
void InterfaceOne.InterfaceMethod()
{
Console.WriteLine("Which interface method is this?");
}
void InterfaceTwo.InterfaceMethod()
{
Console.WriteLine("Which interface method is this?");
}
}
interface InterfaceOne
{
void InterfaceMethod();
}
interface InterfaceTwo
{
void InterfaceMethod();
}
The following link has an excellent video explaining this concept
Explicit Interface Implementation
There is one more way to look at it, from the labyrinthine implementation itself, here: http://blogs.msdn.com/cbrumme/archive/2003/05/03/51381.aspx.
But in short, implicit implementation gives you an is-a type conversion, explicit implementation won't be accessible unless the object is explicitly type cast to that interface type.

What's the point of using an abstract class? [duplicate]

This question already has answers here:
When to use abstract classes?
(6 answers)
Interface vs Abstract Class (general OO)
(36 answers)
Closed 9 years ago.
I know it's a noob question, but I must ask it nonetheless: what is the purpose of using an abstract class?
Let's say I want to extract data from 10 different gambling websites. So I create an abstract class with abstract methods and I override those methods in each of my 10 classes (1 for each website - since each website has a different DOM).
The method in the abstract class does nothing really. Why can't I just declare a method with the same name to each one of my 10 classes?
Same question for Interface.
It's vital for a concept in OOP (and other programming paradigms as well) called polymorphism. In your example, it allows you to say something all those objects have in common, and while the implementation is specific to each class, it says all of them should have it, that's something that characterizes them.
Polymorphism allows one to generalize anything in common, and often may avoid boilerplate code by giving a higher level of abstraction.
Quoting from Wikipedia:
In programming languages and type theory, polymorphism (from Greek πολύς, polys, "many, much" and μορφή, morphē, "form, shape") is the provision of a single interface to entities of different types. A polymorphic type is a type whose operations can also be applied to values of some other type, or types. There are several fundamentally different kinds of polymorphism:
If a function denotes different and potentially heterogeneous implementations depending on a limited range of individually specified types and combinations, it is called ad hoc polymorphism. Ad hoc polymorphism is supported in many languages using function overloading.
If the code is written without mention of any specific type and thus can be used transparently with any number of new types, it is called parametric polymorphism. In the object-oriented programming community, this is often known as generics or generic programming. In the functional programming community, this is often simply called polymorphism.
Subtyping (or inclusion polymorphism) is a concept wherein a name may denote instances of many different classes as long as they are related by some common superclass. In object-oriented programming, this is often referred to simply as polymorphism.
Your example does not fit the real purpose of abstract classes. Try to read some like this:
http://docs.oracle.com/javase/tutorial/java/IandI/abstract.html
It gives your program structure. You can maybe have an abstract base class called BaseScraper and then have derived classes for each site you want to scrape from each with a method called scrape(). You could then add an instance of each scraper to an array and iterate through this array calling Scrape() on each instance to gather data. If you wanted to add another site you would just need to create another derived class that implements the Scrape() method and add it to your array of scrapers. You would not need to change any of your other code, the new scraper would then be incorporated automatically.
There are several reasons for the different approaches. Consider the following:
public abstract class MyAbstractBaseClass
{
String m_url;
public MyAbstractClass(String url)
{
m_url = url;
}
public abstract String GetSiteData();
}
public class SiteAGetter : MyAbstractBaseClass
{
// ...
public override String GetSiteData()
{
// ...
}
}
With this abstract method, you are forced by the compiler to really implement the GetSiteData() method in every overriding implementation. You could, of course, just implement the GetSiteData in the base class as
public virtual String GetSiteData()
{
return null;
}
But now you don't need to implement the method in derived classes and you would need to make sure at every place where you call the method that the return value is non-null before you use it. So basically it is a help to yourself to prevent any obvious errors (you do not want anyone to write a derived class which does not implement that method). Also, an abstract class cannot directly be instantiated, so no one will make the mistake of creating an instance of the base class, because the compiler prevents it.
Interfaces serve a slightly different purpose: They can be implemented by different, unrelated classes. So if for some reason you cannot create a common base, but you want several classes to expose the same interface (= to offer the same functionality) but they are not related, use an interface. Interfaces are also used for other reasons, such as Mocking in unit test environments. There's even more to this, I suggest you read some good book about it and then ask more specific questions.

How to constrait a generic class to work with just two classes

I have a generic class modeling a protocol that encapsulates other protocols. All the protocols implement a specific interface but this generic class must contain only one of two of these protocols as in the real world the other combinations do not exist.
Is there a way to specify the two allowed classes?
Currently I have:
public class ProtocolEncapsulator<TContainedCommand> : IBaseCommand where TContainedCommand : IBaseCommand
But this allows users of the framework to create non-sense combinations.
Thanks
I would suggest creating an interface that is implemented only by the two protocols and then use a type constraint to restrict the method in question.
Something like:
public interface IExclusiveCommand : IBaseCommand
{
void ExclusiveMethod(); //Not necessary if there are no differences between Base and Exclusive
}
public class ProtocolEncapsulator<TContainedCommand> : IBaseCommand where TContainedCommand : IExclusiveCommand
{
}
While it does add another interface and might be viewed as adding complexity, I believe it actually simplifies things by making them more explicit and clear. And the compile-time restriction makes it more maintainable and easier to troubleshoot.

C# - Interface -Help in power of Interface

I am new to C#. Recently I have read an article.It suggests
"One of the practical uses of interface is, when an interface reference is created that can
work on different kinds of objects which implements that interface."
Base on that I tested (I am not sure my understanding is correct)
namespace InterfaceExample
{
public interface IRide
{
void Ride();
}
abstract class Animal
{
private string _classification;
public string Classification
{
set { _classification = value;}
get { return _classification;}
}
public Animal(){}
public Animal(string _classification)
{
this._classification = _classification;
}
}
class Elephant:Animal,IRide
{
public Elephant(){}
public Elephant(string _majorClass):base(_majorClass)
{
}
public void Ride()
{
Console.WriteLine("Elephant can ride 34KPM");
}
}
class Horse:Animal,IRide
{
public Horse(){}
public Horse(string _majorClass):base(_majorClass)
{
}
public void Ride()
{
Console.WriteLine("Horse can ride 110 KPH");
}
}
class Test
{
static void Main()
{
Elephant bully = new Elephant("Vertebrata");
Horse lina = new Horse("Vertebrata");
IRide[] riders = {bully,lina};
foreach(IRide rider in riders)
{
rider.Ride();
}
Console.ReadKey(true);
}
}
}
Questions :
Beyond such extend, what are the different way can we leverage the elegance of Interfaces ?
What is the Key point that I can say this can be only done by interface (apart from
multiple inheritances) ?
(I wish to gather the information from experienced hands).
Edit :
Edited to be concept centric,i guess.
The point is, you could also have a class Bike which implements IRide, without inheriting from Animal. You can think of an interface as being an abstract contract, specifying that objects of this class can do the things specified in the interface.
Because C# doesn't support multiple inheritance (which is a good thing IMHO) interfaces are the way you specify shared behavior or state across otherwise unrelated types.
interface IRideable
{
void Ride();
}
class Elephant : Animal, IRideable{}
class Unicycle: Machine, IRideable{}
In this manner, say you had a program that modeled a circus (where machines and animals had distinct behavior, but some machines and some animals could be ridden) you can create abstract functionality specific to what is means to ride something.
public static void RideThemAll(IEnumerable<IRideable> thingsToRide)
{
foreach(IRideable rideable in thingsToRide)
ridable.Ride();
}
As Lucero points out, you could implement other classes that implement IRide without inherting from Animal and be able to include all of those in your IRide[] array.
The problem is that your IRide interface is still too broad for your example. Obviously, it needs to include the Ride() method, but what does the Eat() method have to do with being able to ride a "thing"?
Interfaces should thought of as a loose contract that guarantees the existance of a member, but not an implementation. They should also not be general enough to span "concepts" (eating and riding are two different concepts).
You are asking the difference between abstract classes and interfaces. There is a really good article on that here.
Another great advantage is lower coupling between software components. Suppose you want to be able to feed any rideable animal. In this case you could write the following method:
public void Feed(IRide rideable)
{
//DO SOMETHING IMPORTANT HERE
//THEN DO SOMETHING SPECIFIC TO AN IRide object
rideable.Eat();
}
The major advantage here is that you can develop and test the Feed method without having any idea of the implementation of IRide passed in to this method. It could be an elephant, horse, or donkey. It doesn't matter. This also opens up your design for using Inversion of Control frameworks like Structure Map or mocking tools like Rhino Mock.
Interfaces can be used for "tagging" concepts or marking classes with specifically functionality such as serializable. This metadata (Introspection or Reflection) can be used with powerful inversion-of-control frameworks such as dependency injection.
This idea is used throughout the .NET framework (such as ISerializable) and third-party DI frameworks.
You already seem to grasp the general meaning of Interfaces.
Interfaces are just a contract saying "I support this!" without saying how the underlying system works.
Contrast this to a base or abstract class, which says "I share these common properties & methods, but have some new ones of my own!"
Of course, a class can implement as many interfaces as it wants, but can only inherit from one base class.

Why do both the abstract class and interface exist in C#?

Why do both the abstract class and interface exist in C# if we can achieve the interface feature by making all the members in the class as abstract.
Is it because:
Interface exists to have multiple inheritance
It makes sense to have interface because object's CAN-DO feature should be placed in an interface rather base abstract class.
Please clarify
Well, an abstract class can specify some implemetation, but usually not all of it. (Having said which, it's perfectly possible to provide an abstract class with no abstract members, but plenty of virtual ones which with "no-op" implementations). An interface provides no implementation, merely a contract.
You could certainly argue that if multiple inheritance of classes were permitted, interfaces would be largely pointless.
Personally I don't get hung up on the whole "is-a" vs "can-do" distinction for inheritance. It never gives me as good an intuition about what to do as just playing around with different ideas and seeing which ones feel the most flexible. (Then again, I'm very much a "favour composition over inheritance" guy...)
EDIT: Just as the most convenient way of rebutting lbushkin's third point in his comment... you can override an abstract method with a non-virtual one (in terms of not being able to override it further) by sealing it:
public abstract class AbstractBase
{
public abstract void Foo();
}
public class Derived : AbstractBase
{
public sealed override void Foo() {}
}
Classes deriving from Derived cannot override Foo any further.
I'm not in any way suggesting I want multiple inheritance of implementation - but if we did have it (along with its complexity) then an abstract class which just contained abstract methods would accomplish almost everything that an interface does. (There's the matter of explicit interface implementation, but that's all I can think of at the moment.)
It's not a trivial question, it's a very good question and one I always ask any candidates I interview.
In a nutshell - an abstract base class defines a type hierarchy whereas an interface defines a contract.
You can see it as is a vs implements a.
i.e
Account could be an abstract base account because you could have a CheckingAccount, a SavingsAccount, etc all which derive from the abstract base class Account. Abstract base classes may also contain non abstract methods, properties and fields just like any normal class. However interfaces only contain abstract methods and properties that must be implemented.
c# let's you derive from one base class only - single inheritance just like java. However you can implement as many interfaces as you like - this is because an interface is just a contract which your class promises to implement.
So if I had a class SourceFile then my class could choose to implement ISourceControl which says 'I faithfully promise to implement the methods and properties that ISourceControl requires'
This is a big area and probably worthy of a better post than the one I've given however I'm short on time but I hope that helps!
They both exist because they are both very different things. Abstract classes permit implementation and interfaces do not. An interface is very handy as it allows me to to say something about the type I am building (it is serializable, it is edible, etc.) but it does not allow me to define any implementation for the members I define.
An abstract class is more powerful that an interface in the sense that it allows me to create an inheritance interface via abstract and virtual members but also provide some sort of default or base implementation if I so choose. As Spiderman knows, however, with that great power comes great responsibility as an abstract class is more architecturally brittle.
Side Note: Something interesting to note is that Vance Morrrison (of the CLR team) has speculated about adding default method implementations to interfaces in a future version of the CLR. This would greatly blur the distinction between an interface and an abstract class. See this video for details.
One important reason both mechanisms exist because c#.NET only allows single inheritance, not multiple inheritance like C++. The class inheritance allows you to inherit implementation from only one place; everything else must be accomplished by implementing interfaces.
For example, let's suppose I create a class, like Car and I subclass into three subclasses, RearWheelDrive, FrontWheelDrive, and AllWheelDrive. Now I decide that I need to cut my classes along a different "axis," like those with push-button starters and those without. I want all pushbutton start cars to have a "PushStartButton()" method and non-pushbutton cars to have a "TurnKey()" method and I want to be able to treat Car objects (with regard to starting them) irrespective of which subclass they are. I can define interfaces that my classes can implement, such as IPushButtonStart and IKeyedIgnition, so I have a common way to deal with my objects that differ in a way that is independent of the single base class from which each derives.
You gave a good answer already. I think your second answer is the real reason. If I wanted to make an object Compareable I shouldn't have to derive from a Comparable base class. if you think of all the interfaces think of all the permutations you'd beed to handle the basic interfaces like IComparable.
Interfaces let us define a contract around the publicly exposed behavior an object provides. Abstract classes let you define both behavior and implementation, which is a very different thing.
Interfaces exist to provide a class without any implementation whatsoever, so that .NET can provide support for safe and functional multiple inheritance in a managed environment.
An Interface defines a contract that an implementing class must fulfil; it is a way of stating that "this does that". An Abstract Class is a partial implementation of a class which is by definition incomplete, and which needs a derviation to be completed. They're very different things.
An abstract class can have an implementation while an interface just allows you to create a contract that implementers have to follow. With abstract classes you can provide a common behavior to their sub classes witch you can't with interfaces.
They serve two distinctly different purposes.
Abstract classes provide a way to have a an object inherit from a defined contract, as well as allowing behavior to be specified in the base class. This, from a theoretical standpoint, provides an IS-A relationship, in that the concrete class IS-A specific type of the base class.
Interfaces allow classes to define a (or more than one) contract which they will fulfill. They allow for a ACTS-AS or "can be used as an" type of relationship, as opposed to direct inheritance. This is why, typically, interfaces will use an adjective as they're name (IDisposable) instead of a noun.
An interface is used for what a class can do, but it is also used to hide some of things that a class can do.
For example the IEnumerable<T> interface describes that a class can iterate through it's members, but it's also limits the access to this single ability. A List<T> can also access the items by index, but when you access it through the IEnumerable<T> interface, you only know about it's ability to iterate the members.
If a method accepts the IEnumerable<T> interface as a parameter, that means that it's only interrested in the ability to iterate through the members. You can use several different classes with this ability (like a List<T> or an array T[]) without the need for one method for each class.
Not only can a method accept several different classes that implement an interface, you can create new classes that implement the interface and the method will happily accept those too.
The idea is simple - if your class(YourClass) is already deriving from a parent class(SomeParentClass) and at the same time you want your class(YourClass) to have a new behavior that is defined in some abstract class(SomeAbstractClass), you can't do that by simply deriving from that abstract class(SomeAbstractClass), C# doesn't allow multiple inheritance.
However if your new behavior was instead defined in an interface (IYourInterface), you could easily derive from the interface(IYourInterface) along with parent class(SomeParentClass).
Consider having a class Fruit that is derived by two children(Apple & Banana) as shown below:
class Fruit
{
public virtual string GetColor()
{
return string.Empty;
}
}
class Apple : Fruit
{
public override string GetColor()
{
return "Red";
}
}
class Banana : Fruit
{
public override string GetColor()
{
return "Yellow";
}
}
We have an existing interface ICloneable in C#. This interface has a single method as shown below, a class that implements this interface guarantees that it can be cloned:
public interface ICloneable
{
object Clone();
}
Now if I want to make my Apple class(not Banana class) clonable, I can simpley implement ICloneable like this:
class Apple : Fruit , ICloneable
{
public object Clone()
{
// add your code here
}
public override string GetColor()
{
return "Red";
}
}
Now considering your argument of pure abstract class, if C# had a pure abstract class say Clonable instead of interface IClonable like this:
abstract class Clonable
{
public abstract object Clone();
}
Could you now make your Apple class clonable by inheriting the abstract Clonable instead of IClonable? like this:
// Error: Class 'Apple' cannot have multiple base classes: 'Fruit' & 'Clonable'
class Apple : Fruit, Clonable
{
public object Clone()
{
// add your code here
}
public override string GetColor()
{
return "Red";
}
}
No, you can't, because a class cannot derive from multiple classes.

Categories

Resources