Java 支持多重继承吗?为什么?我们如何解决这个问题?

java 8object oriented programmingprogramming更新于 2024/11/11 21:03:00

每当您扩展一个类时,子类对象都可以获得超类成员的副本,并且您可以使用子类的对象调用超类的方法。

示例

在下面的例子中,我们有一个名为 SuperClass 的类,其方法名为 demo()。我们正在用另一个类(SubClass)扩展此类。

现在,您创建子类的对象并调用方法 demo()

class SuperClass{
   public void demo() {
      System.out.println("demo method");
   }
}
public class SubClass extends SuperClass {
   public static void main(String args[]) {
      SubClass obj = new SubClass();
      obj.demo();
   }
}

输出

demo method

java 中的多重继承

假设我们有两个类,即 SuperClass1 和 SuperClass2,它们具有相同的方法,例如 demo()(包括参数),如下所示 −

class SuperClass1{
   public void demo() {
      System.out.println("demo method");
   }
}
class SuperClass2{
   public void demo() {
      System.out.println("demo method");
   }
}

现在,从另一个类开始,如果将这两个类扩展为 −

public class SubClass extends SuperClass1, SuperClass2 {
   public static void main(String args[]) {
      SubClass obj = new SubClass();
      obj.demo();
   }
}

根据继承的基本规则,应在子类对象中创建两个 demo() 方法的副本,这样子类将保留两个具有相同原型的方法。然后,如果您使用子类的对象调用 demo() 方法,编译器将面临一个模棱两可的情况,不知道该调用哪个方法。

因此,在 Java 中不允许多重继承,并且您不能扩展多个其他类。但是,如果您尝试这样做,则会产生编译时错误。

编译时错误

在编译时,上述程序会产生以下错误 −

MultipleInheritanceExample.java:9: error: '{' expected
public class MultipleInheritanceExample extends MyInterface1, MyInterface2{
                                                               ^
1 error

使用接口实现多重继承

如果多个接口具有相同的默认方法。在实现两个接口的具体类中,您可以实现公共方法并调用两个超方法。因此,您可以使用接口在 Java 中实现多重继承。

示例

interface MyInterface1{
   public static int num = 100;
   public default void display() {
      System.out.println("display method of MyInterface1");
   }
}
interface MyInterface2{
   public static int num = 1000;
   public default void display() {
      System.out.println("display method of MyInterface2");
   }
}

public class InterfaceExample implements MyInterface1, MyInterface2{
   public void display() {
      System.out.println("This is the implementation of the display method");
   }
   public void show() {
      MyInterface1.super.display();
      MyInterface2.super.display();
   }

   public static void main(String args[]) {
      InterfaceExample obj = new InterfaceExample();
      obj.show();
   }
}

输出

display method of MyInterface1
display method of MyInterface2

相关文章