Why is Multiple Inheritance not allowed in Java or

2019-01-01 03:43发布

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?

17条回答
初与友歌
2楼-- · 2019-01-01 04:03

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.

查看更多
看淡一切
3楼-- · 2019-01-01 04:03

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:

Multiple Inheritance Ambiguity with Interface

查看更多
步步皆殇っ
4楼-- · 2019-01-01 04:05

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.

查看更多
唯独是你
5楼-- · 2019-01-01 04:06

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
        }
    }
    
查看更多
零度萤火
6楼-- · 2019-01-01 04:07

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.

查看更多
谁念西风独自凉
7楼-- · 2019-01-01 04:10

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.

查看更多
登录 后发表回答