java如何变相支持多重继承_Java是否支持多重继承?为什么?我们该如何解决呢?...

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

示例

在下面的示例中,我们有一个名为SuperClass的类,其类名为name 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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值