Multiple inheritance means that a subclass can inherit from multiple parent classes at the same time, thus having the characteristics of multiple parent classes at the same time, but the disadvantages are significant.
1. If the parent class inherited by a subclass has the same member variable, the subclass will not be able to determine which parent class member variable to use when referencing the variable.
For example:
public class classA // 父类 classA { private int num = 0; } public class classB // 父类 classB { private int num = 1; } public class classC extends classA,classB // 子类 classC 继承于 classA 和 classB { public static void main(String [] args) { classC obj = new classC(); obj.print(); // 调用父类成员变量 num , 那 num 等于 0 还是 1 ? } public void print() { System.out.println(super.num); } }
2. If multiple parent classes inherited by a subclass have the same method, and the subclass does not override the method (if covered, then If you directly use this method in the subclass), you will not be able to determine which parent class method to call when calling this method.
For example:
public class classA // 父类 classA { public void fun() { System.out.print("hello"); } } public class classB // 父类 classB { public void fun() { System.out.print("hello"); } } public class classC extends classA,classB { public static void main(String [] args) { classC t = new classC(); t.print(); } public void print() { super.fun(); // 调用父类中 fun 方法,但由于classA、classB都有fun()方法,将无法确定使用 // 哪个父类中的方法 } }
Therefore, Java only allows single inheritance, that is, a subclass can only inherit from one parent class. But in order to expand the functionality of subclasses, Java uses interfaces to overcome the shortcomings of not using multiple inheritance.
The interface is a special abstract class. The member variables in the interface default to static final types, that is, constants, and the methods in the interface are abstract and have no method bodies.
Specific methods can only be implemented by the class that implements the interface. When calling, only the method of the implementing class will always be called (there is no ambiguity), so there is no second disadvantage of multiple inheritance; and because of the interface There are only static constants, but since static variables determine the calling relationship at compile time, even if there is a certain conflict, an error will be prompted at compile time; when referencing static variables, generally use the class name or interface name directly to avoid ambiguity. Therefore The first disadvantage of multiple inheritance does not exist either. These shortcomings also do not exist when an interface inherits multiple parent interfaces.
The above is the detailed content of Why can't java have multiple inheritance?. For more information, please follow other related articles on the PHP Chinese website!