温馨提示×

java怎么继承多个父类

小亿
105
2023-10-25 10:09:15
栏目: 编程语言

在Java中,Java不支持多继承。但是,你可以通过实现多个接口来达到类似多继承的效果。通过实现多个接口,一个类可以获得多个父类的特性。

下面是一个示例代码:

interface Interface1 {
    void method1();
}

interface Interface2 {
    void method2();
}

class MyClass implements Interface1, Interface2 {
    public void method1() {
        System.out.println("Implementing method1");
    }

    public void method2() {
        System.out.println("Implementing method2");
    }
}

public class Main {
    public static void main(String[] args) {
        MyClass myClass = new MyClass();
        myClass.method1();
        myClass.method2();
    }
}

在上面的示例中,MyClass类实现了Interface1Interface2这两个接口。通过实现这两个接口,MyClass类可以调用method1method2方法,从而获得了两个父类的特性。

0