As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
I have come across numerous arguments against the inclusion of multiple inheritance in C#, some of which include (philosophical arguments aside):
Multiple inheritance is too complicated and often ambiguous
It is unnecessary because interfaces provide something similar
Composition is a good substitute where interfaces are inappropriate
I come from a C++ background and miss the power and elegance of multiple inheritance. Although it is not suited to all software designs there are situations where it is difficult to deny it's utility over interfaces, composition and similar OO techniques.
Is the exclusion of multiple inheritance saying that developers are not smart enough to use them wisely and are incapable of addressing the complexities when they arise?
I personally would welcome the introduction of multiple inheritance into C# (perhaps C##).
Addendum: I would be interested to know from the responses who comes from a single (or procedural background) versus a multiple inheritance background. I have often found that developers who have no experience with multiple inheritance will often default to the multiple-inheritance-is-unnecessary argument simply because they do not have any experience with the paradigm.
I've never missed it once, not ever. Yes, it [MI] gets complicated, and yes, interfaces do a similar job in many ways - but that isn't the biggest point: in the general sense, it simply isn't needed most of the time. Even single inheritance is overused in many cases.
Prefer aggregation over inheritance!
class foo : bar, baz
is often better handled with
class foo : Ibarrable, Ibazzable
{
...
public Bar TheBar{ set }
public Baz TheBaz{ set }
public void BarFunction()
{
TheBar.doSomething();
}
public Thing BazFunction( object param )
{
return TheBaz.doSomethingComplex(param);
}
}
This way you can swap in and out different implementations of IBarrable and IBazzable to create multiple versions of the App without having to write yet another class.
Dependency injection can help with this a lot.
One of the issues with dealing with multiple inheritance is the distinction between interface inheritance and implementation inheritance.
C# already has a clean implementation of interface inheritance (including choice of implicit or explicit implementations) by using pure interfaces.
If you look at C++, for each class you specify after the colon in the class declaration, the kind of inheritance you get is determined by the access modifier (private, protected, or public). With public inheritance, you get the full messiness of multiple inheritance—multiple interfaces are mixed with multiple implementations. With private inheritance, you just get implementation. An object of "class Foo : private Bar" can never get passed to a function that expects a Bar because it's as if the Foo class really just has a private Bar field and an automatically-implemented delegation pattern.
Pure multiple implementation inheritance (which is really just automatic delegation) doesn't present any problems and would be awesome to have in C#.
As for multiple interface inheritance from classes, there are many different possible designs for implementing the feature. Every language that has multiple inheritance has its own rules as to what happens when a method is called with the same name in multiple base classes. Some languages, like Common Lisp (particularly the CLOS object system), and Python, have a meta-object protocol where you can specify the base class precedence.
Here's one possibility:
abstract class Gun
{
public void Shoot(object target) {}
public void Shoot() {}
public abstract void Reload();
public void Cock() { Console.Write("Gun cocked."); }
}
class Camera
{
public void Shoot(object subject) {}
public virtual void Reload() {}
public virtual void Focus() {}
}
//this is great for taking pictures of targets!
class PhotoPistol : Gun, Camera
{
public override void Reload() { Console.Write("Gun reloaded."); }
public override void Camera.Reload() { Console.Write("Camera reloaded."); }
public override void Focus() {}
}
var pp = new PhotoPistol();
Gun gun = pp;
Camera camera = pp;
pp.Shoot(); //Gun.Shoot()
pp.Reload(); //writes "Gun reloaded"
camera.Reload(); //writes "Camera reloaded"
pp.Cock(); //writes "Gun cocked."
camera.Cock(); //error: Camera.Cock() not found
((PhotoPistol) camera).Cock(); //writes "Gun cocked."
camera.Shoot(); //error: Camera.Shoot() not found
((PhotoPistol) camera).Shoot();//Gun.Shoot()
pp.Shoot(target); //Gun.Shoot(target)
camera.Shoot(target); //Camera.Shoot(target)
In this case, only the first listed class's implementation is implicitly inherited in the case of a conflict. The class for other base types must be explicitly specified to get at their implementations. To make it more idiot-proof, the compiler can disallow implicit inheritance in the case of a conflict (conflicting methods would always require a cast).
Also, you can implement multiple inheritance in C# today with implicit conversion operators:
public class PhotoPistol : Gun /* ,Camera */
{
PhotoPistolCamera camera;
public PhotoPistol() {
camera = new PhotoPistolCamera();
}
public void Focus() { camera.Focus(); }
class PhotoPistolCamera : Camera
{
public override Focus() { }
}
public static Camera implicit operator(PhotoPistol p)
{
return p.camera;
}
}
It's not perfect, though, as it's not supported by the is and as operators, and System.Type.IsSubClassOf().
Here is a very useful case for multiple inheritance that I run into all of the time.
As a toolkit vendor, I cannot change published API's or I will break backwards compatibility. One thing that results from that is that I cannot ever add to an interface once I have released it because it would break compilation for anyone implementing it -- the only option is to extend the interface.
This is fine for existing customers, but new ones would see this hierarchy as needlessly complex, and if I were designing it from the beginning, I would not opt to implement it this way -- I have to, or else I will lose backwards compatibility. If the interface is internal, then I just add to it and fix the implementors.
In many cases, the new method to the interface has an obvious and small default implementation, but I cannot provide it.
I would prefer to use abstract classes and then when I have to add a method, add a virtual one with a default implementation, and sometimes we do this.
The issue, of course, is if this class would likely be mixed in to something that is already extending something -- then we have no choice but to use an interface and deal with extension interfaces.
If we think we have this problem in a big way, we opt for a rich event model instead -- which I think is probably the right answer in C#, but not every problem is solved this way -- sometimes you want a simple public interface, and a richer one for extenders.
C# supports single inheritance, interfaces and extension methods. Between them, they provide just about everything that multiple inheritance provides, without the headaches that multiple inheritance brings.
Multiple inheritance isn't supported by the CLR in any way I'm aware of, so I doubt it could be supported in an efficient way as it is in C++ (or Eiffel, which may do it better given that the language is specifically designed for MI).
A nice alternative to Multiple Inheritance is called Traits. It allows you to mix together various units of behavior into a single class. A compiler can support traits as a compile-time extension to the single-inheritance type system. You simply declare that class X includes traits A, B, and C, and the compiler puts the traits you ask for together to form the implementation of X.
For example, suppose you are trying to implement IList(of T). If you look at different implementations of IList(of T), they often share some of the exact same code. That's were traits come in. You just declare a trait with the common code in it and you can use that common code in any implementation of IList(of T) -- even if the implementation already has some other base class. Here's what the syntax might look like:
/// This trait declares default methods of IList<T>
public trait DefaultListMethods<T> : IList<T>
{
// Methods without bodies must be implemented by another
// trait or by the class
public void Insert(int index, T item);
public void RemoveAt(int index);
public T this[int index] { get; set; }
public int Count { get; }
public int IndexOf(T item)
{
EqualityComparer<T> comparer = EqualityComparer<T>.Default;
for (int i = 0; i < Count; i++)
if (comparer.Equals(this[i], item))
return i;
return -1;
}
public void Add(T item)
{
Insert(Count, item);
}
public void Clear()
{ // Note: the class would be allowed to override the trait
// with a better implementation, or select an
// implementation from a different trait.
for (int i = Count - 1; i >= 0; i--)
RemoveAt(i);
}
public bool Contains(T item)
{
return IndexOf(item) != -1;
}
public void CopyTo(T[] array, int arrayIndex)
{
foreach (T item in this)
array[arrayIndex++] = item;
}
public bool IsReadOnly
{
get { return false; }
}
public bool Remove(T item)
{
int i = IndexOf(item);
if (i == -1)
return false;
RemoveAt(i);
return true;
}
System.Collections.IEnumerator
System.Collections.IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
IEnumerator<T> GetEnumerator()
{
for (int i = 0; i < Count; i++)
yield return this[i];
}
}
And you use the trait like this:
class MyList<T> : MyBaseClass, DefaultListMethods<T>
{
public void Insert(int index, T item) { ... }
public void RemoveAt(int index) { ... }
public T this[int index] {
get { ... }
set { ... }
}
public int Count {
get { ... }
}
}
Of course, I'm just scratching the surface here. For a more complete description, see the paper Traits: Composable Units of Behavior (PDF).
The Rust language (from Mozilla) has implemented Traits in an interesting way: they noticed that traits are similar to default interface implementations, so they unified interfaces and traits into a single feature (which they call traits). The main difference between traits and default interface implementations (which Java now has) is that traits can contain private or protected methods, unlike traditional interface methods that must be public. If traits and interfaces are not unified into a single feature, then another difference is that you can have a reference to an interface, but you can't have a reference to a trait; a trait is not itself a type.
I actually miss multiple inheritance for one specific reason... the dispose pattern.
EVERY time that I need to implement the dispose pattern, I say to myself: "I wish I could just derive from a class that implements the dispose pattern with a few virtual overrides." I copy and paste the same boiler-plate code into every class that implements IDispose and I hate it.
I would argue against multiple inheritance simply for the reason you state. Developers will misuse it. I've seen enough problems with every class inheriting from a utility class, just so you can call a function from every class without needing to type so much, to know that multiple inheritance would lead to bad code in many situations. The same thing could be said about GoTo, which is one of the reasons it's use is so frowned upon. I think that multiple inheritance does have some good uses, just like GoTo, In an ideal world, where they were both only used when appropriately, there would be no problems. However, the world is not ideal, so we must protect bad programmers from themselves.
YES! YES! and YES!
Seriously, I've been developing GUI libraries my entire career, and MI (Multiple Inheritance) makes this FAR easier than SI (Single Inheritance)
First I did SmartWin++ in C++ (MI heavily used) then I did Gaia Ajax and finally now Ra-Ajax and I can with extreme confident state that MI rules for some places. One of those places being GUI libraries...
And the arguments claiming that MI "is too complex" and such are mostly put there by people trying to construct language wars and happens to belong to the camp which "currently doesn't have MI"...
Just like functional programming languages (like Lisp) have been taught (by the "non-Lispers") as "too complex" by non-functional programming language advocates...
People are afraid of the unknown...
MI RULES!
I'm happy that C# does not have Multiple Inheritance, even though it would sometimes be convenient. What I would like to see instead is the ability to provide a default implementation of an interface method. That is:
interface I
{
void F();
void G();
}
class DefaultI : I
{
void F() { ... }
void G() { ... }
}
class C : I = DefaultI
{
public void F() { ... } // implements I.F
}
In this case, ((I)new C()).F() will call C's implementation of I.F(), while ((I)new C()).G() will call DefaultI's implementation of I.G().
There are a number of issues that the language designers would have to work out before this could be added to the language, but none that are very hard, and the result would cover many of the needs that make Multiple Inheritance desirable.
I have been working with C# since it was first available as an alpha/beta release and have never missed multiple inheritance. MI is nice for some things but there are almost always other ways to achieve the same result (some of which actually end up being simpler or creating an easier to understand implementation).
Multiple inheritance in general can be useful and many OO languages implement it one way or another (C++, Eiffel, CLOS, Python...). Is it essential? No. Is it nice to have? Yes.
Update
I challenge everyone who votes me down to show me any example of multiple inheritance that I can't easily port to a language with single inheritance. Unless anyone can show any such sample, I claim it does not exist. I have ported tons of C++ code (MH) to Java (no-MH) and that was never a problem, no matter how much MH the C++ code used.
Nobody could ever prove so far that multiple inheritance has any advantage over other techniques you mentioned in your post (using interfaces and delegates I can get exactly the same result without much code or overhead), while it has a couple of well known disadvantages (diamond problem being the most annoying ones).
Actually multiple inheritance is usually abused. If you use OO design to somehow model the real world into classes, you will never get to the point where multiple inheritance makes actually sense. Can you provide a useful example for multiple inheritance? Most of the examples I've seen so far are actually "wrong". They make something a subclass, that is in fact just an extra property and thus actually an interface.
Take a look at Sather. It is a programming language, where interfaces do have multiple inheritance, as why not (it can't create a diamond problem), however classes that are no interfaces have no inheritance whatsoever. They can only implement interfaces and they can "include" other objects, which makes these other objects a fixed part of them, but that is not the same as inheritance, it's rather a form of delegation (method calls "inherited" by including objects are in fact just forwarded to instances of these objects encapsulated in your object). I think this concept is pretty interesting and it shows you can have a complete clean OO language without any implementation inheritance at all.
No.
(for voting)
one of the truly nice and (at the time) novel things about the DataFlex 4GL v3+ (I know, I know, Data what?) was its support for mixin inheritance - the methods from any other classes could be reused in your class; as long as your class provided the properties that these methods used, it worked just fine, and there was no "diamond problem" or other multiple-inheritance "gotchas" to worry about.
i would like to see something like this in C# as it would simplify certain kinds of abstraction and contruction issues
Instead of multiple inheritance, you can use mixins which is a better solution.
I think it would over-complicate things without providing enough ROI. We already see people butcher .NET code with too-deep inheritance trees. I can just imagine the atrocities if people had the power to do multiple inheritance.
I won't deny that it has potential, but I just don't see enough benefit.
While there are certainly instances where it can be useful, I have found that most of the time when I think I need it, I really don't.
A colleague wrote this blog about how to get something like multiple inheritance in C# with Dynamic Compilation:
http://www.atalasoft.com/cs/blogs/stevehawley/archive/2008/09/29/late-binding-in-c-using-dynamic-compilation.aspx
I think its simple really. Just like any other complex programming paradigm, you can misuse it and hurt yourself. Can you misuse objects (oh yes!), but that doesn't mean OO is bad in itself.
Similarly with MI. If you do not have a large 'tree' of inherited classes, or a lot of classes that provide the same named methods, then you will be perfectly fine with MI. In fact, as MI provides the implementation, you'll often be better off than a SI implementation where you have to re-code, or cut&paste methods to delegated objects. Less code is better in these cases.. you can make an almighty mess of sharing code by trying to re-use objects through interface inheritance. And such workarounds don't smell right.
I think the single-inheritance model of .NET is flawed: they should have gone with interfaces only, or MI only. Having "half and half" (ie single implementation inheritance plus multiple interface inheritance) is more confusing than it should be, and not elegant at all.
I come from a MI background, and I'm not scared of or burnt by it.
I have posted this here a couple of times but I just think it is really cool. You can learn how to fake MI here. I also think the article highlights why MI is such a pain even if that was not intended.
I neither miss it or need it, I prefer to use composition of objects to achieve my ends. That is really the point of the article as well.
I've used multiple inheritence in C++ myself too, but you really have to know what you're doing in order to not get yourself in trouble, especially if you have two base classes which share a grandparent. Then you can get into issues with virtual inheritence, having to declare every constructor you're going to call down the chain (which makes binary reuse much harder)... it can be a mess.
More importantly, the way the CLI is currently built precludes MI from being implemented easily. I'm sure they could do it if they wanted, but I have other things I'd rather see in the CLI than multiple inheritence.
Things I'd like to see include some features of Spec#, like non-nullable reference types. I'd also like to see more object safety by being able to declare parameters as const, and the ability to declare a function const (meaning that you are guaranteeing that the internal state of an object won't be changed by the method and the compiler double checks you).
I think that between Single Inheritence, Multiple Interface Inheritence, Generics, and Extension Methods, you can do pretty much anything you need to. If anything could improve things for someone desiring MI, I think some sort of language construct which would would allow easier aggregation and composition is needed. That way you can have a shared interface, but then delegate your implementation to a private instance of the class you would normally inherit from. Right now, that takes a lot of boiler plate code to do. Having a more automated language feature for that would help significantly.
I prefer C++. I've used Java, C#, etc. As my programs get more sophisticated in such an OO environment, I find myself missing Multiple Inheritance. That's my subjective experience.
It can make for amazing spaghetti code...it can make for amazingly elegant code.
I believe languages like C# should give the programmer the option. Just because it maybe too complicated does not mean it will be too complicated. Programming languages should provide the developer with tools to build anything the programmer wants to.
You choose to use those API's a developer already wrote, you dont have too.
Give C# implicits and you will not miss multiple inheritance, or any inheritance for that matter.
No I do not. I use all other OO features to develop what I want. I use Interface and object encapsulation and I am never limited on what I want to do.
I try not to use inheritance. The less I can everytime.
No unless Diamond problem is solved. and you can use composition till this is not solved.
No, we came away from it. You do need it now.
If we introduce Multiple Inheritance then we are again facing the old Diamond problem of C++...
However for those who think it's unavoidable we can still introduce multiple inheritance effects by means of composition (Compose multiple objects in an object and expose public methods which delegate responsibilities to composed object and return)...
So why bother to have multiple inheritance and make your code vulnerable to unavoidable exceptions...
Related
As a premise one of a key difference of FP design about reusable libraries (for what I'm learning), is that these are more data-centric that corresponding OO (in general).
This seems confirmed also from emerging techniques like TFD (Type-First-Development), well explained by Tomas Petricek in this blog post.
Nowadays language are multi-paradigm and the same Petricek in its book explains various functional techniques usable from C#.
What I'm interested here and, hence the question, is how to properly partition code.
So I've defined library data structures, using the equivalent of discriminated unions (as shown in Petricek book), and I project to use them with immutable lists and/or tuples according to the domain logic of mine requirements.
Where do I place operations (methods ... functions) that acts on data structures?
If I want define an high-order function that use a function value embodied in a standard delegates Func<T1...TResult>, where do I place it?
Common sense says me to group these methods in static classes, but I'd like a confirmation from people that already wrote functional libs in C#.
Assuming that this is correct and I've an high-order function like this:
static class AnimalTopology {
IEnumerable<Animal> ListVertebrated(Func<Skeleton, bool> selector) {
// remainder omitted
}
}
If choosing vertebrated animal has N particular cases that I want to expose in the library, what's the more correct way to expose them.
static class VertebratedSelectorsA {
// this is compatible with "Func<Skeleton, bool> selector"
static bool Algorithm1(Skeleton s) {
//...
}
}
or
static class VertebratedSelectorsB {
// this method creates the function for later application
static Func<Skeleton, bool> CreateAlgorithm1Selector(Skeleton s) {
// ...
}
}
Any indication will be very appreciated.
EDIT:
I want to quote two phrases from T. Petricek, Real World Functional Programming foreword by Mads Torgersen:
[...] You can use functional programming techniques in C# to great benefit,
though it is easier and more natural to do so in F#.
[...]
Functional programming is a state of mind. [...]
EDIT-2:
I feel there's a necessity to further clarify the question. The functional mentioned in the title strictly relates to Functional Programming; I'm not asking the more functional way of grouping methods, in the sense of more logic way or the the way that make more sense in general.
This implies that the implementation will try to follow as more as possible founding concepts of FP summarized by NOOO manifesto and quoted here for convenience and clarity:
Functions and Types over classes
Purity over mutability
Composition over inheritance
Higher-order functions over method dispatch
Options over nulls
The question is around how to layout a C# library wrote following FP concepts, so (for example) it's absolutely not an option putting methods inside data structure; because this is a founding Object-Oriented paradigm.
EDIT-3:
Also if the question got response (and various comments), I don't want give the wrong impression that there has been said that one programming paradigm is superior than another.
As before I'll mention an authority on FP, Don Syme, in its book Expert F# 3.0 (ch.20 - Designing F# Libraries - pg.565):
[...] It's a common misconception that the functional and OO programming methodologies compete; in fact, they're largely orthogonal. [...]
Note: If you want a shorter, more-to-the-point answer, see my other answer. I am aware that this one here might seem to ramble & go on forever & talk past your issue, but perhaps it will give you a few ideas.
It is difficult to answer your question without knowing the exact relationship between Animal and Skeleton. I will make a recommendation about this relationship in the second half of my answer, but before I do that, I will simply go along with what I see in your post.
First I will try to infer a few things from your code:
static class AnimalTopology
{
// Note: I made this function `static`... or did you omit the keyword on purpose?
static IEnumerable<Animal> ListVertebrated(Func<Skeleton, bool> selector)
{
…
}
}
If you have designed that function according to functional principles, it should have no side-effects. That is, its output relies only on its arguments. (And in a semi-object-oriented setting, perhaps on other static members of AnimalTopology; but since you didn't show any, let us ignore that possibility.)
If the function is indeed side-effect-free (and does not access static members of AnimalTopology), then the function's type signature suggests that it is possible to derive an Animal from a Skeleton, because it accepts something that acts on Skeletons and returns Animals.
If this is also true, then let me assume the following for the sake of being able to give an answer:
class Skeleton
{
…
public Animal Animal { get { … } } // Skeletons have animals!? We'll get to that.
}
Now it is obvious that your function is impossible to implement, since it could derive Animals from Skeletons, but it doesn't receive any Skeleton at all; it only receives a predicate function that acts on a Skeleton. (You could fix this by adding a second parameter of type Func<IEnumerable<Skeleton>> getSkeletons, but...)
In my opinion, something like the following would make more sense:
static IEnumerable<Animal> GetVertebrates(this IEnumerable<Skeleton> skeletons,
Func<Skeleton, bool> isVertebrate)
{
return skeletons
.Where(isVertebrate)
.Select(s => s.Animal);
}
Now, one might wonder why you are guessing animals from their skeletons; and isn't the bool property "is vertebrate" an inherent property of an animal (or skeleton)? Are there really several ways to decide on this?
I would suggest the following:
class Animal
{
Skeleton Skeleton { get; } // not only vertebrates have skeletons!
}
class Vertebrate : Animal { … } // vertebrates are a kind of animal
static class AnimalsExtensions
{
static IEnumerable<Vertebrate> ThatAreVertebrates(this IEnumerable<Animal> animals)
{
return animals.OfType<Vertebrate>();
}
}
Please note the use of extension methods above. Here's an example how to use it:
List<Animal> animals = …;
IEnumerable<Vertebrate> vertebrates = animals.ThatAreVertebrates();
Now suppose your extension method did more complex work. In that case, it might be a good idea to put it inside its own designated "algorithm type":
interface IVertebrateSelectionAlgorithm
{
IEnumerable<Vertebrate> GetVertebrates(IEnumerable<Animal> animals);
}
This has the advantage that it can be set up / parameterized e.g. via a class constructor; and you could split up the algorithm into several methods that all reside in the same class (but are all private except for GetVertebrates.)
Of course you can do the same kind of parameterization with functional closures, but in my experience that quickly gets messy in a C# setting. Here, classes are a good means to group a set of functions together as one logical entity.
Where do I place operations (methods ... functions) that acts on data structures?
I see four common approaches (in no particular order):
Put the functions inside the data structures. (This is the object-oriented "method" approach. It is suitable when a function acts only on an instance of that type. It is perhaps less appropriate e.g. when a function "draws together" several objects of different types, and spits out an object of yet another type. In this case, I would...)
Put the functions inside their own designated "algorithm classes". (This seems reasonable when the functions do much or complex work, or need to be parameterized/configured, or where you might want to split the algorithm into several functions that you can then logically "group" together by putting them in a class type.)
Turn the functions into lambdas (a.k.a. anonymous delegates, closures, etc.). (This works well if they're small and you only need them in one specific place; the code won't be easily reusable in a different place.)
Put the functions in a static class and make them extension methods. (That's how LINQ to Objects works. It is a hybrid functional & object-oriented approach. It takes some extra care to get the discoverability / namespacing issue right. Many people will think this approach breaks "encapsulation" when taken too far. For a counter-argument, read the excellent C++ article "How Non-Member Functions Improve Encapsulation"; substitute "extension method" for "non-member friend function".)
Note: I could go into each of these in more detail if people want, but before I do that, I'll wait and see what kind of feedback this answer receives.
Is it bad policy to have lots of "work" classes(such as Strategy classes), that only do one thing?
Let's assume I want to make a Monster class. Instead of just defining everything I want about the monster in one class, I will try to identify what are its main features, so I can define them in interfaces. That will allow to:
Seal the class if I want. Later, other users can just create a new class and still have polymorphism by means of the interfaces I've defined. I don't have to worry how people (or myself) might want to change/add features to the base class in the future. All classes inherit from Object and they implement inheritance through interfaces, not from mother classes.
Reuse the strategies I'm using with this monster for other members of my game world.
Con: This model is rigid. Sometimes we would like to define something that is not easily achieved by just trying to put together this "building blocks".
public class AlienMonster : IWalk, IRun, ISwim, IGrowl {
IWalkStrategy _walkStrategy;
IRunStrategy _runStrategy;
ISwimStrategy _swimStrategy;
IGrowlStrategy _growlStrategy;
public Monster() {
_walkStrategy = new FourFootWalkStrategy();
...etc
}
public void Walk() { _walkStrategy.Walk(); }
...etc
}
My idea would be next to make a series of different Strategies that could be used by different monsters. On the other side, some of them could also be used for totally different purposes (i.e., I could have a tank that also "swims"). The only problem I see with this approach is that it could lead to a explosion of pure "method" classes, i.e., Strategy classes that have as only purpose make this or that other action. In the other hand, this kind of "modularity" would allow for high reuse of stratagies, sometimes even in totally different contexts.
What is your opinion on this matter? Is this a valid reasoning? Is this over-engineering?
Also, assuming we'd make the proper adjustments to the example I gave above, would it be better to define IWalk as:
interface IWalk {
void Walk();
}
or
interface IWalk {
IWalkStrategy WalkStrategy { get; set; } //or something that ressembles this
}
being that doing this I wouldn't need to define the methods on Monster itself, I'd just have public getters for IWalkStrategy (this seems to go against the idea that you should encapsulate everything as much as you can!)
Why?
Thanks
Walk, Run, and Swim seem to be implementations rather than interfaces. You could have a ILocomotion interface and allow your class to accept a list of ILocomotion implementations.
Growl could be an implementation of something like an IAbility interface. And a particular monster could have a collection of IAbility implementations.
Then have an couple of interfaces that is the logic of which ability or locomotion to use: IMove, IAct for example.
public class AlienMonster : IMove, IAct
{
private List<IAbility> _abilities;
private List<ILocomotion> _locomotions;
public AlienMonster()
{
_abilities = new List<IAbility>() {new Growl()};
_locomotion = new List<ILocomotion>() {new Walk(), new Run(), new Swim()}
}
public void Move()
{
// implementation for the IMove interface
}
public void Act()
{
// implementation for the IAct interface
}
}
By composing your class this way you will avoid some of the rigidity.
EDIT: added the stuff about IMove and IAct
EDIT: after some comments
By adding IWalk, IRun, and ISwim to a monster you are saying that anything can see the object should be able to call any of the methods implemented in any of those interfaces and have it be meaningful. Further in order for something to decide which of the three interfaces it should use you have to pass the entire object around. One huge advantage to using an interface is that you can reference it by that interface.
void SomeFunction(IWalk alienMonster) {...}
The above function will take anything that implements IWalk but if there are variations of SomeFunction for IRun, ISwim, and so on you have to write a whole new function for each of those or pass the AlienMonster object in whole. If you pass the object in then that function can call any and all interfaces on it. It also means that that function has to query the AlienMonster object to see what its capabilities are and then decide which to use. All of this ends up making external a lot of functionality that should be kept internal to class. Because you are externalizing all of that and there is not commonality between IWalk, IRun, ISwim so some function(s) could innocently call all three interfaces and your monster could be running-walking-swimming at the same time. Further since you will want to be able to call IWalk, IRun, ISwim on some classes, all classes will basically have to implement all three interfaces and you'll end up making a strategy like CannotSwim to satisfy the interface requirement for ISwim when a monster can't swim. Otherwise you could end up trying call an interface that isn't implemented on a monster. In the end you are actually making the code worse for the extra interfaces, IMO.
In languages which support multiple inheritance, you could indeed create your Monster by inheriting from classes which represent the things it can do. In these classes, you would write the code for it, so that no code has to be copied between implementing classes.
In C#, being a single inheritance language, I see no other way than by creating interfaces for them. Is there a lot of code shared between the classes, then your IWalkStrategy approach would work nicely to reduce redundant code. In the case of your example, you might also want to combine several related actions (such as walking, swimming and running) into a single class.
Reuse and modularity are Good Things, and having many interfaces with just a few methods is in my opinion not a real problem in this case. Especially because the actions you define with the interfaces are actually different things which may be used differently. For example, a method might want an object which is able to jump, so it must implement that interface. This way, you force this restriction by type at compile time instead of some other way throwing exceptions at run time when it doesn't meet the method's expectations.
So in short: I would do it the same way as you proposed, using an additional I...Strategy approach when it reduces code copied between classes.
From a maintenance standpoint, over-abstraction can be just as bad as rigid, monolithic code. Most abstractions add complication and so you have to decide if the added complexity buys you something valuable. Having a lot of very small work classes may be a sign of this kind of over-abstraction.
With modern refactoring tools, it's usually not too difficult to create additional abstraction where and when you need it, rather than fully architecting a grand design up-front. On projects where I've started very abstractly, I've found that, as I developed the concrete implementation, I would discover cases I hadn't considered and would often find myself trying to contort the implementation to match the pattern, rather than going back and reconsidering the abstraction. When I start more concretely, I identify (more of) the corner cases ahead of time and can better determine where it really makes sense to abstract.
"Find what varies and encapsulate it."
If how a monster walks varies, then encapsulate that variation behind an abstraction. If you need to change how a monster walks, you have probably have a state pattern in your problem. If you need to make sure that the Walk and Growl strategies agree, then you probably have an abstract factory pattern.
In general: no, it is definitely not over-engineering to encapsulate various concepts into their own classes. There is also nothing wrong with making concrete classes sealed or final, either. It forces people to consciously break encapsulation before inheriting from something that probably should not be inherited.
I am still having trouble understanding what interfaces are good for. I read a few tutorials and I still don't know what they really are for other then "they make your classes keep promises" and "they help with multiple inheritance".
Thats about it. I still don't know when I would even use an interface in a real work example or even when to identify when to use it.
From my limited knowledge of interfaces they can help because if something implements it then you can just pass the interface in allowing to pass in like different classes without worrying about it not being the right parameter.
But I never know what the real point of this since they usually stop short at this point from showing what the code would do after it passes the interface and if they sort of do it it seems like they don't do anything useful that I could look at and go "wow they would help in a real world example".
So what I guess I am saying is I am trying to find a real world example where I can see interfaces in action.
I also don't understand that you can do like a reference to an object like this:
ICalculator myInterface = new JustSomeClass();
So now if I would go myInterface dot and intellisense would pull up I would only see the interface methods and not the other methods in JustSomeClass. So I don't see a point to this yet.
Also I started to do unit testing where they seem to love to use interfaces but I still don't understand why.
Like for instance this example:
public AuthenticationController(IFormsAuthentication formsAuth)
{
FormsAuth = formsAuth ?? new FormsAuthenticationWrapper();
}
public class FormsAuthenticationWrapper : IFormsAuthentication
{
public void SetAuthCookie(string userName, bool createPersistentCookie)
{
FormsAuthentication.SetAuthCookie(userName, createPersistentCookie);
}
public void SignOut()
{
FormsAuthentication.SignOut();
}
}
public IFormsAuthentication FormsAuth
{
get;
set;
}
Like why bother making this interface? Why not just make FormsAuthenticationWrapper with the methods in it and call it a day? Why First make an interface then have the Wrapper implement the interface and then finally write the methods?
Then I don't get what the statement is really saying.
Like I now know that the statement is saying this
FormsAuth = formsAuth ?? new FormsAuthenticationWrapper();
if formsAuth is null then make a new FormsAuthenticationWrapper and then assign it to the property that is an Interface.
I guess it goes back to the whole point of why the reference thing. Especially in this case since all the methods are exactly the same. The Wrapper does not have any new methods that the interface does not have and I am not sure but when you do this the methods are filled right(ie they have a body) they don't get converted to stubs because that would really seem pointless to me(it it would be converted back to an interface).
Then in the testing file they have:
var formsAuthenticationMock = new Mock<AuthenticationController.IFormsAuthentication>();
So they just pass in the FormsAuthentication what I am guessing makes all the fake stubs. I am guessing the wrapper class is used when the program is actually running since it has real methods that do something(like sign a person out).
But looking at new Mock(from moq) it accepts a class or an interface. Why not just again made the wrapper class put those methods in and then in the new Mock call that?
Would that not just make the stubs for you?
Ok, I had a hard time understanding too at first, so don't worry about it.
Think about this, if you have a class, that lets say is a video game character.
public class Character
{
}
Now say I want to have the Character have a weapon. I could use an interface to determin the methods required by a weapon:
interface IWeapon
{
public Use();
}
So lets give the Character a weapon:
public class Character
{
IWeapon weapon;
public void GiveWeapon(IWeapon weapon)
{
this.weapon = weapon;
}
public void UseWeapon()
{
weapon.Use();
}
}
Now we can create weapons that use the IWeapon interface and we can give them to any character class and that class can use the item.
public class Gun : IWeapon
{
public void Use()
{
Console.Writeline("Weapon Fired");
}
}
Then you can stick it together:
Character bob = new character();
Gun pistol = new Gun();
bob.GiveWeapon(pistol);
bob.UseWeapon();
Now this is a general example, but it gives a lot of power. You can read about this more if you look up the Strategy Pattern.
Interfaces define contracts.
In the example you provide, the ?? operator just provides a default value if you pass null to the constructor and doesn't really have anything to do with interfaces.
What is more relevant is that you might use an actual FormsAuthenticationWrapper object, but you can also implement your own IFormsAuthentication type that has nothing to do with the wrapper class at all. The interface tells you what methods and properties you need to implement to fulfill the contract, and allows the compiler to verify that your object really does honor that contract (to some extent - it's simple to honor a contract in name, but not in spirit), and so you don't have to use the pre-built FormsAuthenticationWrapper if you don't want to. You can build a different class that works completely differently but still honors the required contract.
In this respect interfaces are much like normal inheritance, with one important difference. In C# a class can only inherit from one type but can implement many interfaces. So interfaces allow you to fulfill multiple contracts in one class. An object can be an IFormsAuthentication object and also be something else, like IEnumerable.
Interfaces are even more useful when you look at it from the other direction: they allow you to treat many different types as if they were all the same. A good example of this is with the various collections classes. Take this code sample:
void OutputValues(string[] values)
{
foreach (string value in values)
{
Console.Writeline(value);
}
}
This accepts an array and outputs it to the console. Now apply this simple change to use an interface:
void OutputValues(IEnumerable<string> values)
{
foreach (string value in values)
{
Console.Writeline(value);
}
}
This code still takes an array and outputs it to the console. But it also takes a List<string> or anything else you care to give it that implements IEnumerable<string>. So we've taken an interface and used it to make a simple block of code much more powerful.
Another good example is the ASP.Net membership provider. You tell ASP.Net that you honor the membership contract by implementing the required interfaces. Now you can easily customize the built-in ASP.Net authentication to use any source, and all thanks to interfaces. The data providers in the System.Data namespace work in a similar fashion.
One final note: when I see an interface with a "default" wrapper implementation like that, I consider it a bit of an anit-pattern, or at least a code smell. It indicates to me that maybe the interface is too complicated, and you either need to split it apart or consider using some combination of composition + events + delegates rather than derivation to accomplish the same thing.
Perhaps the best way to get a good understanding of interfaces is to use an example from the .NET framework.
Consider the following function:
void printValues(IEnumerable sequence)
{
foreach (var value in sequence)
Console.WriteLine(value);
}
Now I could have written this function to accept a List<T>, object[], or any other type of concrete sequence. But since I have written this function to accept a parameter of type IEnumerable that means that I can pass any concrete type into this function that implements the IEnumerable interface.
The reason this is desirable is that by using the interface type your function is more flexible than it would otherwise be. Also you are increasing the utility of this function as many different callers will be able to make use of it without requiring modification.
By using an interface type you are able to declare the type of your parameter as a contract of what you need from whatever concrete type is passed in. In my example I don't care what type you pass me, I just care that I can iterate it.
All of the answers here have been helpful and I doubt I can add anything new to the mix but in reading the answers here, two of the concepts mentioned in two different answers really meshed well in my head so I will compose my understanding here in the hopes that it might help you.
A class has methods and properties and each of the methods and properties of a class has a signature and a body
public int Add(int x, int y)
{
return x + y;
}
The signature of the Add method is everything before the first curly brace character
public int Add(int x, int y)
The purpose of the method signature is to assign a name to a method and also to describe it's protection level (public, protected, internal, private and / or virtual) which defines where a method can be accessed from in code
The signature also defines the type of the value returned by the method, the Add method above returns an int, and the arguments a method expects to have passed to it by callers
Methods are generally considered to be something an object can do, the example above implies that the class the method is defined in works with numbers
The method body describes precisly (in code) how it is that an object performs the action described by the method name. In the example above the add method works by applying the addition operator to it's parameters and returing the result.
One of the primary differences between an interface and a class in terms of language syntax is that an interface can only define the signature of a methd, never the method body.
Put another way, an interface can describe in a the actions (methods) of a class, but it must never describe how an action is to be performed.
Now that you hopefully have a better understanding of what an interface is, we can move on to the second and third parts of your question when, and why would we use an interface in a real program.
One of the main times interfaces are used in a program is when one wants to perform an action, without wanting to know, or be tied to the specifics of how those actions are performed.
That is a very abstract concept to grapsp so perhaps an example might help to firm things up in your mind
Imagine you are the author of a very popular web browser that millions of people use every day and you have thousands of feature requests from people, some big, some little, some good and some like "bring back <maquee> and <blink> support".
Because you only have a relitivly small number of developers, and an even smaller number of hours in the day, you can't possibly implement every requested feature yourself, but you still want to satisfy your customers
So you decide to allow users to develop their own plugins, so they can <blink 'till the cows come home.
To implement this you might come up with a plugin class that looks like:
public class Plugin
{
public void Run (PluginHost browser)
{
//do stuff here....
}
}
But how could you reasonably implement that method? You can't possibly know precisly how every poossible future plugin is going to work
One possible way around this is to define Plugin as an interface and have the browser refer to each plugin using that, like this:
public interface IPlugin
{
void Run(PluginHost browser);
}
public class PluginHost
{
public void RunPlugins (IPlugin[] plugins)
{
foreach plugin in plugins
{
plugin.Run(this);
}
}
}
Note that as discussed earlier the IPlugin interface describes the Run method but does not specify how Run does it's job because this is specific to each plugin, we don't want the plugin host concerned with the specifics of each individual plugin.
To demonstrate the "can-be-a" aspect of the relationship between a class and an interface I will write a plugin for the plugin host below that implements the <blink> tag.
public class BlinkPlugin: IPlugin
{
private void MakeTextBlink(string text)
{
//code to make text blink.
}
public void Run(PluginHost browser)
{
MakeTextBlink(browser.CurrentPage.ParsedHtml);
}
}
From this perspective you can see that the plugin is defined in a class named BlinkPlugin but because it also implements the IPlugin interface it can also be refered to as an IPlugin object,as the PluginHost class above does, because it doesn't know or care what type the class actually is, just that it can be an IPlugin
I hope this has helped, I really didnt intend it to be quite this long.
I'll give you an example below but let me start with one of your statements. "I don't know how to identify when to use one". to put it on edge. You don't need to identify when to use it but when not to use it. Any parameter (at least to public methods), any (public) property (and personally I would actually extend the list to and anything else) should be declared as something of an interface not a specific class. The only time I would ever declare something of a specific type would be when there was no suitable interface.
I'd go
IEnumerable<T> sequence;
when ever I can and hardly ever (the only case I can think off is if I really needed the ForEach method)
List<T> sequence;
and now an example. Let's say you are building a sytem that can compare prices on cars and computers. Each is displayed in a list.
The car prices are datamined from a set of websites and the computer prices from a set of services.
a solution could be:
create one web page, say with a datagrid and Dependency Injection of a IDataRetriever
(where IDataRetriver is some interface making data fetching available with out you having to know where the data came from (DB,XML,web services or ...) or how they were fetched (data mined, SQL Quering in house data or read from file).
Since the two scenarios we have have nothing but the usage in common a super class will make little sense. but the page using our two classes (one for cars and one for computers) needs to perform the exact same operations in both cases to make that possible we need to tell the page (compiler) which operations are possible. We do that by means of an interface and then the two classes implement that interfcae.
using dependency injection has nothing to do with when or how to use interfaces but the reason why I included it is another common scenario where interfaces makes you life easier. Testing. if you use injection and interfaces you can easily substitute a production class for a testing class when testing. (This again could be to switch data stores or to enforce an error that might be very hard to produce in release code, say a race condition)
We use interfaces (or abstract base classes) to allow polymorphism, which is a very central concept in object-oriented programming. It allows us to compose behavior in very flexible ways. If you haven't already, you should read Design Patterns - it contains numerous examples of using interfaces.
In relation to Test Doubles (such as Mock objects), we use interfaces to be able to remove functionality that we currently don't want to test, or that can't work from within a unit testing framework.
Particularly when working with web development, a lot of the services that we rely on (such as the HTTP Context) isn't available when the code executes outside of the web context, but if we hide that functionality behind an interface, we can replace it with something else during testing.
The way I understood it was:
Derivation is 'is-a' relationship e.g., A Dog is an Animal, A Cow is an Animal but an interface is never derived, it is implemented.
So, interface is a 'can-be' relationship e.g., A Dog can be a Spy Dog, A Dog can be a Circus Dog etc. But to achieve this, a dog has to learn some specific things. Which in OO terminology means that your class has to able to do some specific things (contract as they call it) if it implements an interface. e.g., if your class implements IEnumerable, it clearly means that your class has (must have) such a functionality that it's objects can be Enumerated.
So, in essence, through Interface Implementation a Class exposes a functionality to its users that it can do something and it is NOT inheritance.
With almost everything written about interfaces, let me have a shot.
In simple terms, interface is something which will relate two or more , otherwise, non related classes.
Interfaces define contract which ensures that any two or more classes, even if not completely related, happens to implement a common interface, will contain a common set of operations.
Combined with the support of polymorphism , one can use interfaces to write cleaner and dynamic code.
eg.
Interface livingBeings
-- speak() // says anybody who IS a livingBeing need to define how they speak
class dog implements livingBeings
--speak(){bark;} // implementation of speak as a dog
class bird implements livingBeings
--speak(){chirp;}// implementation of speak as a bird
ICalculator myInterface = new JustSomeClass();
JustSomeClass myObject = (JustSomeClass) myInterface;
Now you have both "interfaces" to work with on the object.
I am pretty new to this too, but I like to think of interfaces as buttons on a remote control. When using the ICalculator interface, you only have access to the buttons (functionality) intended by the interface designer. When using the JustSomeClass object reference, you have another set of buttons. But they both point to the same object.
There are many reasons to do this. The one that has been most useful to me is communication between co-workers. If they can agree on an interface (buttons which will be pushed), then one developer can work on implementing the button's functionality and another can write code that uses the buttons.
Hope this helps.
I know that multiple inheritance is not allowed in Java and C#. Many books just say, multiple inheritance is not allowed. But it can be implemented by using interfaces. Nothing is discussed about why it is not allowed. Can anybody tell me precisely why it is not allowed?
The short answer is: because the language designers decided not to.
Basically, it seemed that both the .NET and Java designers did not allow multiple inheritance because they reasoned that adding MI added too much complexity to the languages while providing too little benefit.
For a more fun and in-depth read, there are some articles available on the web with interviews of some of the language designers. For example, for .NET, Chris Brumme (who worked at MS on the CLR) has explained the reasons why they decided not to:
Different languages actually have different expectations for how MI
works. For example, how conflicts are
resolved and whether duplicate bases
are merged or redundant. Before we can
implement MI in the CLR, we have to do
a survey of all the languages, figure
out the common concepts, and decide
how to express them in a
language-neutral manner. We would also
have to decide whether MI belongs in
the CLS and what this would mean for
languages that don't want this concept
(presumably VB.NET, for example). Of
course, that's the business we are in
as a common language runtime, but we
haven't got around to doing it for MI
yet.
The number of places where MI is truly appropriate is actually quite
small. In many cases, multiple
interface inheritance can get the job
done instead. In other cases, you may
be able to use encapsulation and
delegation. If we were to add a
slightly different construct, like
mixins, would that actually be more
powerful?
Multiple implementation inheritance injects a lot of complexity into the
implementation. This complexity
impacts casting, layout, dispatch,
field access, serialization, identity
comparisons, verifiability,
reflection, generics, and probably
lots of other places.
You can read the full article here.
For Java, you can read this article:
The reasons for omitting multiple
inheritance from the Java language
mostly stem from the "simple, object
oriented, and familiar" goal. As a
simple language, Java's creators
wanted a language that most developers
could grasp without extensive
training. To that end, they worked to
make the language as similar to C++ as
possible (familiar) without carrying
over C++'s unnecessary complexity
(simple).
In the designers' opinion, multiple
inheritance causes more problems and
confusion than it solves. So they cut
multiple inheritance from the language
(just as they cut operator
overloading). The designers' extensive
C++ experience taught them that
multiple inheritance just wasn't worth
the headache.
Multiple inheritance of implementation is what is not allowed.
The problem is that the compiler/runtime cannot figure out what to do if you have a Cowboy and an Artist class, both with implementations for the draw() method, and then you try to create a new CowboyArtist type. What happens when you call the draw() method? Is someone lying dead in the street, or do you have a lovely watercolor?
I believe it's called the double diamond inheritance problem.
Reason:
Java is very popular and easy to code, because of its simplicity.
So what ever java developers feel difficult and complicated to understand for programmers, they tried to avoid it. One such kind of property is multiple inheritance.
They avoided pointers
They avoided multiple inheritance.
Problem with multiple inheritance: Diamond problem.
Example:
Assume that class A is having a method fun(). class B and class C derives from class A.
And both the classes B and C, overrides method fun().
Now assume that class D inherits both class B, and C. (just Assumption)
Create object for class D.
D d = new D();
and try to access d.fun(); => will it call class B's fun() or class C's fun()?
This is the ambiguity existing in diamond problem.
It is not impossible to solve this problem, but it creates more confusion and complexities to the programmer while reading it.
It causes more problem than it tries to solve.
Note: But any way you can always implement multiple inheritance indirectly by using interfaces.
Because Java has a greatly different design philosophy from C++. (I'm not going to discuss C# here.)
In designing C++, Stroustrup wanted to include useful features, regardless of how they could be misused. It's possible to screw up big-time with multiple inheritance, operator overloading, templates, and various other features, but it's also possible to do some very good things with them.
The Java design philosophy is to emphasize safety in language constructs. The result is that there are things that are a lot more awkward to do, but you can be a lot more confident that the code you're looking at means what you think it does.
Further, Java was to a large extent a reaction from C++ and Smalltalk, the best known OO languages. There are plenty of other OO languages (Common Lisp was actually the first one to be standardized), with different OO systems that handle MI better.
Not to mention that it's entirely possible to do MI in Java, using interfaces, composition, and delegation. It's more explicit than in C++, and therefore is clumsier to use but will get you something you're more likely to understand at first glance.
There is no right answer here. There are different answers, and which one is better for a given situation depends on applications and individual preference.
The main (although by no means the only) reason people steer away from MI is the so called "diamond problem" leading to ambiguity in your implementation. This wikipedia article discusses it and explains better than I could. MI can also lead to more complex code, and a lot of OO designers claim that you do't need MI, and if you do use it your model is probably wrong. I'm not sure I agree with this last point, but keeping things simple is always a good plan.
In C++ multiple inheritance was a major headache when used improperly. To avoid those popular design issues multiple interfaces "inheritance" was forced instead in modern languages (java, C#).
Multiple Inheritance is
hard to understand
hard to debug (for example, if you mix classes from multiple frameworks that have identically-named methods deep down, quite unexpected synergies can occur)
easy to mis-use
not really that useful
hard to implement, especially if you want it done correctly and efficiently
Therefore, it can be considered a wise choice to not include Multiple Inheritance into the Java language.
Another reason is that single-inheritance makes casting trivial, emitting no assembler instructions (other than checking for the compatibility of the types where required). If you had multiple-inheritance, you'd need to figure out where in the child class a certain parent starts. So performance is certainly a perk (although not the only one).
Back in the old days ('70s) when Computer Science was more Science and less mass production the programmers had time to think about good design and good implementation and as a result the products (programms) had high quality ( eg. TCP/IP design and implementation ).
Nowadays, when everybody is programming, and the managers are changing the specs before deadlines, subtle issues like the one descriped in the wikipedia link from Steve Haigh post are difficult to track; therefore, the "multiple inheritance" is limited by compiler design. If you like it, you can still use C++ .... and have all the freedom you want :)
I take the statement that "Multiple inheritance is not allowed in Java" with a pinch of salt.
Multiple Inheritance is defined when a "Type" inherits from more than one "Types". And interfaces are also classified as types as they have behavior. So Java does have multiple inheritance. Just that it is safer.
Dynamic loading of classes makes the implementation of multiple inheritance difficult.
In java actually they avoided the complexity of multiple inheritance instead by using single inheritance and interface.
Complexity of multiple inheritance is very high in a situation like below explained
diamond problem of multiple inheritance.
We have two classes B and C inheriting from A. Assume that B and C are overriding an inherited method and they provide their own implementation. Now D inherits from both B and C doing multiple inheritance. D should inherit that overridden method, jvm can't able to decide which overridden method will be used?
In c++ virtual functions are used to handle and we have to do explicitly.
This can be avoided by using interfaces, there are no method bodies. Interfaces cannot be instantiated—they can only be implemented by classes or extended by other interfaces.
Actually multiple inheritance will arise a the complexity if the inherited classes have same function. ie the compiler will have a confusion which one has to chose (diamond problem). So in Java that complexity removed and gave interface to get the functionality like multiple inheritance gave. We can use interface
Java has concept, i.e. polymorphism. There are 2 types of polymorphism in java. There are method overloading and method overriding. Among them, method overriding happens with super- and subclass relationship. If we are creating an object of a subclass and invoking the method of superclass, and if subclass extends more than one class, which super class method should be called?
Or , while calling superclass constructor by super(), which super class constructor will get called?
This decisions are impossible by current java API features. so multiple inheritance is not allowed in java.
Multiple Inheritance is not allowed in Java directly , but through interfaces it is allowed.
Reason :
Multiple Inheritance : Introduces more complexity and ambiguity.
Interfaces : Interfaces are completely abstract classes in Java that provide you with a uniform way to properly delineate the structure or inner workings of your program from its publicly available interface, with the consequence being a greater amount of flexibility and reusable code as well as more control over how you create and interact with other classes.
More precisely, they are a special construct in Java with the additional characteristic that allow you to perform a kind of multiple inheritance i.e. classes that can be upcast to more than one class.
Lets take simple example.
Suppose there are 2 superclasses classes A and B with same method names but different functionalities. Through following code with (extends) keyword multiple inheritance is not possible.
public class A
{
void display()
{
System.out.println("Hello 'A' ");
}
}
public class B
{
void display()
{
System.out.println("Hello 'B' ");
}
}
public class C extends A, B // which is not possible in java
{
public static void main(String args[])
{
C object = new C();
object.display(); // Here there is confusion,which display() to call, method from A class or B class
}
}
But through interfaces, with (implements) keyword multiple inheritance is possible.
interface A
{
// display()
}
interface B
{
//display()
}
class C implements A,B
{
//main()
C object = new C();
(A)object.display(); // call A's display
(B)object.display(); //call B's display
}
}
Can anybody tell me precisely why it is not allowed?
You can find answer from this documentation link
One reason why the Java programming language does not permit you to extend more than one class is to avoid the issues of multiple inheritance of state, which is the ability to inherit fields from multiple classes
If multiple inheritance is allowed and when you create an object by instantiating that class, that object will inherit fields from all of the class's super classes. It will cause two issues.
What if methods or constructors from different super classes instantiate the same field?
Which method or constructor will take precedence?
Even though multiple inheritance of state is now allowed, still you can implement
Multiple inheritance of type: Ability of a class to implement more than one interface.
Multiple inheritance of implementation (through default methods in interfaces) : Ability to inherit method definitions from multiple classes
Refer to this related SE question for additional info:
Multiple Inheritance Ambiguity with Interface
In C++ a class can inherit (directly or indirectly) from more than one class, which is referred to as
multiple inheritance.
C# and Java, however, limit classes to single inheritance each class inherits
from a single parent class.
Multiple inheritance is a useful way to create classes that combine aspects of two disparate class
hierarchies, something that often happens when using different class frameworks within a single
application.
If two frameworks define their own base classes for exceptions, for example, you can
use multiple inheritance to create exception classes that can be used with either framework.
The problem with multiple inheritance is that it can lead to ambiguity. The classic example is when
a class inherits from two other classes, each of which inherits from the same class:
class A {
protected:
bool flag;
};
class B : public A {};
class C : public A {};
class D : public B, public C {
public:
void setFlag( bool nflag ){
flag = nflag; // ambiguous
}
};
In this example, the flag data member is defined by class A. But class D descends from class B
and class C, which both derive from A, so in essence two copies of flag are available because two
instances of A are in D’s class hierarchy. Which one do you want to set? The compiler will complain
that the reference to flag in D is ambiguous. One fix is to explicitly disambiguate the reference:
B::flag = nflag;
Another fix is to declare B and C as virtual base classes, which means that only one copy of A can
exist in the hierarchy, eliminating any ambiguity.
Other complexities exist with multiple inheritance, such as the order in which the base classes are
initialized when a derived object is constructed, or the way members can be inadvertently hidden
from derived classes. To avoid these complexities, some languages restrict themselves to the simpler single inheritance model.
Although this does simplify inheritance considerably, it also limits its usefulness
because only classes with a common ancestor can share behaviors. Interfaces mitigate this
restriction somewhat by allowing classes in different hierarchies to expose common interfaces even
if they’re not implemented by sharing code.
Imagine this Example:
I have a class Shape1
It has CalcualteArea method:
Class Shape1
{
public void CalculateArea()
{
//
}
}
There is another class Shape2 that one also has same method
Class Shape2
{
public void CalculateArea()
{
}
}
Now I have a child class Circle, it derives from both Shape1 and Shape2;
public class Circle: Shape1, Shape2
{
}
Now when I create object for Circle, and call the method, system does not know which calculate area method to be called. Both has same signatures. So compiler will get confuse. That's why multiple inheritances are not allowed.
But there can be multiple interfaces because interfaces do not have method definition. Even both the interfaces have same method, both of them do not have any implementation and always method in the child class will be executed.
I have seen arguments for using explicit interfaces as a method of locking a classes usage to that interface. The argument seems to be that by forcing others to program to the interface you can ensure better decoupling of the classes and allow easier testing.
Example:
public interface ICut
{
void Cut();
}
public class Knife : ICut
{
void ICut.Cut()
{
//Cut Something
}
}
And to use the Knife object:
ICut obj = new Knife();
obj.Cut();
Would you recommend this method of interface implementation? Why or why not?
EDIT:
Also, given that I am using an explicit interface the following would NOT work.
Knife obj = new Knife();
obj.Cut();
To quote GoF chapter 1:
"Program to an interface, not an implementation".
"Favor object composition over class inheritance".
As C# does not have multiple inheritance, object composition and programming to interfaces are the way to go.
ETA: And you should never use multiple inheritance anyway but that's another topic altogether.. :-)
ETA2: I'm not so sure about the explicit interface. That doesn't seem constructive. Why would I want to have a Knife that can only Cut() if instansiated as a ICut?
I've only used it in scenarios where I want to restrict access to certain methods.
public interface IWriter
{
void Write(string message);
}
public interface IReader
{
string Read();
}
public class MessageLog : IReader, IWriter
{
public string Read()
{
// Implementation
return "";
}
void IWriter.Write(string message)
{
// Implementation
}
}
public class Foo
{
readonly MessageLog _messageLog;
IWriter _messageWriter;
public Foo()
{
_messageLog = new MessageLog();
_messageWriter = _messageLog;
}
public IReader Messages
{
get { return _messageLog; }
}
}
Now Foo can write messages to it's message log using _messageWriter, but clients can only read. This is especially beneficial in a scenario where your classes are ComVisible. Your client can't cast to the Writer type and alter the information inside the message log.
Yes. And not just for testing. It makes sense to factor common behaviour into an interface (or abstract class); that way you can make use of polymorphism.
public class Sword: ICut
{
void ICut.Cut()
{
//Cut Something
}
}
Factory could return a type of sharp implement!:
ICut obj = SharpImplementFactory();
obj.Cut();
This is a bad idea because their usage breaks polymorphism. The type of the reference used should NOT vary the behavior of the object. If you want to ensure loose coupling, make the classes internal and use a DI technology (such as Spring.Net).
There are no doubt certain advantages to forcing the users of your code to cast your objects to the interface types you want them to be using.
But, on the whole, programming to an interface is a methodology or process issue. Programming to an interface is not going to be achieved merely by making your code annoying to the user.
Using interfaces in this method does not, in and of itself, lead to decoupled code. If this is all you do, it just adds another layer of obfuscation and probably makes this more confusing later on.
However, if you combine interface based programming with Inversion of Control and Dependency Injection, then you are really getting somewhere. You can also make use of Mock Objects for Unit Testing with this type of setup if you are into Test Driven Development.
However, IOC, DI and TDD are all major topics in and of themselves, and entire books have been written on each of those subjects. Hopefully this will give you a jumping off point of things you can research.
Well there is an organizational advantage. You can encapsulate your ICuttingSurface, ICut and related functionality into an Assembly that is self-contained and unit testable. Any implementations of the ICut interface are easily Mockable and can be made to be dependant upon only the ICut interface and not actual implementations which makes for a more modular and clean system.
Also this helps keep the inheritance more simplified and gives you more flexibility to use polymoprhism.
Allowing only callers expecting to explicit interface type ensures methods are only visible in the context they are needed in.
Consider a logical entity in a game and u decide that instead of a class responsibile for drawing/ticking the entities you want the code for tick/draw to be in the entity.
implement IDrawable.draw() and ITickable.tick() ensures an entity can only ever be drawn/ticked when the game expects it to. Otherwise these methods wont ever be visible.
Lesser bonus is when implementing multiple interfaces, explicit implementations let you work around cases where two interface method names collide.
Another potential scenario for explicitly implementing an interface is when dealing with an existing class that already implements the functionality, but uses a different method name. For example, if your Knife class already had a method called Slice, you could implement the interface this way:
public class Knife : ICut
{
public void Slice()
{
// slice something
}
void ICut.Cut()
{
Slice();
}
}
If the client code doesn't care about anything other than the fact that it can use the object to Cut() things, then use ICut.
Yes, but not necessarily for the given reasons.
An example:
On my current project, we are building a tool for data entry. We have certain functions that are used by all (or almost all) tabs, and we are coding a single page (the project is web-based) to contain all of the data entry controls.
This page has navigation on it, and buttons to interact with all the common actions.
By defining an interface (IDataEntry) that implements methods for each of the functions, and implementing that interface on each of the controls, we can have the aspx page fire public methods on the user controls which do the actual data entry.
By defining a strict set of interaction methods (such as your 'cut' method in the example) Interfaces allow you to take an object (be it a business object, a web control, or what have you) and work with it in a defined way.
For your example, you could call cut on any ICut object, be it a knife, a saw, a blowtorch, or mono filament wire.
For testing purposes, I think interfaces are also good. If you define tests based around the expected functionality of the interface, you can define objects as described and test them. This is a very high-level test, but it still ensures functionality. HOWEVER, this should not replace unit testing of the individual object methods...it does no good to know that 'obj.Cut' resulted in a cutting if it resulted in the wrong thing being cut, or in the wrong place.