JDK1.8新特性之接口中的静态方法与默认方法

一. 新特性概述概述

在Jdk8之前,Interface之中可以定义变量和方法,变量必须为public static final的,由于实现接口中的方法必须要重写它的方法,而子类继承抽象类必须重写其所有的抽象方法,所以接口中的方法必须隐式为public abstract的。JDK1.8中允许我们在接口中定义static方法和default方法

二. 代码示例

Jdk1.8之前,接口中只能有public abstract隐式修饰的抽象方法。

public interface JDK8BeforeInterface {
    
    public static final int field1 = 0;

    public abstract void method1(int a) throws Exception;

    //隐式的被public abstract修饰
    void method2(int a) throws Exception;
}

 

Jdk1.8及以后,允许我们在接口中定义static方法和default方法。

public  interface JDK8Interface {

    //static 修饰定义静态方法
    static void staticMethod(){

       System.out.println("接口中的静态方法。");
    }
    //default修饰符定义默认方法
    default void defaultMethod() {

        System.out.println("接口中的默认方法。");
    }
}

代码解析:

public interface JDK8Interface {

        //static 修饰定义静态方法

        static void staticMethod() {
                System.out.println("接口中的静态方法。");
        }

        //default修饰符定义默认方法 

        default void defaultMethod() {
                 System.out.println("接口中的默认方法。");
        }
}

定义一个接口的实现类:

public class JDK8InterfaceImpl implements JDK8Interface {

    //实现接口后,因为默认方法不是抽象方法,所以可以不重写,但是如果开发需要,也可以重写。
}

静态方法,只能通过接口名来调用,不可以通过实现类的类名或者实现类的对象来调用。default方法,只能够通过接口实现类的对象来调用。

public class Main {

        public static void main(String[] args) {

        //static方法必须通过接口类来调用,不可以通过实现类或者是实现类的对象来调用
        JDK8Interface.staticMethod();

        //default方法必须通过实现类的对象来调用
        new JDK8InterfaceImpl().defaultMethod();
         }
}

当然如果接口中的默认方法不能满足某个实现类需要,那么实现类可以覆盖默认方法。

public class AnOtherJDK8InterfaceImpl implements JDK8Interface {

        @Override
         public void deaultMethod() {
            System.out.println("接口实现类覆盖了接口中的default方法");
        }
}

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值