Java接口类的多继承

首先,从 Java 8 开始,接口可以包含默认方法,使用 default 关键字:

    public interface InterfaceA {
        default void method1() {
            System.out.println("method1 from InterfaceA.");
        }

        default void method2() {
            System.out.println("method2 from InterfaceA.");
        }

        void method3();

        default void method4() {
            System.out.println("method4 from InterfaceA.");
        }

        void method5();

        default void method6() {
            System.out.println("method6 from InterfaceA.");
        }
    }

    public interface InterfaceB {
        default void method1() {
            System.out.println("method1 from InterfaceB.");
        }

        default void method2() {
            System.out.println("method2 from InterfaceB.");
        }

        void method3();

        void method4();

        default void method5() {
            System.out.println("method5 from InterfaceB.");
        }

        default void method7() {
            System.out.println("method7 from InterfaceB.");
        }
    }

接着,接口类 TestService 多继承 InterfaceAInterfaceB

    public interface TestService extends InterfaceA, InterfaceB {
        @Override
        default void method1() {
            InterfaceA.super.method1();
        }

        @Override
        default void method2() {
            InterfaceB.super.method2();
        }

        @Override
        default void method4() {
            InterfaceA.super.method4();
        }

        @Override
        void method5();
    }
  • method3 不用重写,是因为两个父接口均没有默认实现。
  • method6method7 不用重写,是因为两个父接口没有产生冲突。
  • 其余方法都需要 TestService 重写。

最后,实体类 MyClass 实现 TestService

    public static class MyClass implements TestService {
        @Override
        public void method3() {

        }

        @Override
        public void method5() {

        }
    }
  • method1method2method4 不用重写,因为 TestService 重写了这些方法,并添加了默认实现。
  • method3 需要重写,因为所有父接口均没有实现。
  • method5 需要重写,因为 TestService 重写了此方法,但没有具体实现。
  • method6method7 不用重写,因为 TestService 没有重写这些方法,继承了父接口的默认实现。

测试

实际效果,可以通过以下代码进行测试:

    public static void main(String[] args) {
        TestService myClass = new MyClass();
        myClass.method1();
        myClass.method2();
        myClass.method3();
        myClass.method4();
        myClass.method5();
        myClass.method6();
        myClass.method7();
    }
  • 8
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值