Why is Multiple Inheritance not allowed in Java or C#?

C#JavaLanguage DesignMultiple Inheritance

C# Problem Overview


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?

C# Solutions


Solution 1 - C#

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:

> 1. 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. > > 2. 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? > > 3. 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.

Solution 2 - C#

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.

Solution 3 - C#

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.

  1. They avoided pointers
  2. They avoided multiple inheritance.

Problem with multiple inheritance: Diamond problem.

Example:

  1. Assume that class A is having a method fun(). class B and class C derives from class A.
  2. And both the classes B and C, overrides method fun().
  3. Now assume that class D inherits both class B, and C. (just Assumption)
  4. Create object for class D.
  5. D d = new D();
  6. 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.

Solution 4 - C#

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.

Solution 5 - C#

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.

Solution 6 - C#

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

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

Solution 8 - C#

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

Solution 9 - C#

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

Solution 10 - C#

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.

Solution 11 - C#

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.

Solution 12 - C#

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

Solution 13 - C#

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.

Solution 14 - C#

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.

  1. 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
             }
         }
     
    
  2. 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
         }
     }
    
       
    
           
     
           
    

Solution 15 - C#

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

  1. What if methods or constructors from different super classes instantiate the same field?

  2. 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:

https://stackoverflow.com/questions/29758213/multiple-inheritance-ambiguity-with-interface

Solution 16 - C#

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.

Solution 17 - C#

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAbdulsattar MohammedView Question on Stackoverflow
Solution 1 - C#RazzieView Answer on Stackoverflow
Solution 2 - C#duffymoView Answer on Stackoverflow
Solution 3 - C#user1923551View Answer on Stackoverflow
Solution 4 - C#David ThornleyView Answer on Stackoverflow
Solution 5 - C#SteveView Answer on Stackoverflow
Solution 6 - C#inazarukView Answer on Stackoverflow
Solution 7 - C#mfxView Answer on Stackoverflow
Solution 8 - C#BlindyView Answer on Stackoverflow
Solution 9 - C#Cata LinView Answer on Stackoverflow
Solution 10 - C#Rig VedaView Answer on Stackoverflow
Solution 11 - C#sujith sView Answer on Stackoverflow
Solution 12 - C#JinuView Answer on Stackoverflow
Solution 13 - C#Abhay KokateView Answer on Stackoverflow
Solution 14 - C#Chaitra DeshpandeView Answer on Stackoverflow
Solution 15 - C#Ravindra babuView Answer on Stackoverflow
Solution 16 - C#zerocoolView Answer on Stackoverflow
Solution 17 - C#Engr Muhammad Enayet AbdullahView Answer on Stackoverflow