The Default Methods And Static Methods In Java Interface

来源:互联网 发布:linux 安装php环境 编辑:程序博客网 时间:2024/04/30 09:46

Default Methods
Default methods enable you to add new functionality to the interfaces of your libraries and ensure binary compatibility with code written for older versions of those interfaces

默认方法主要是在确保不破坏原有程序的基础上对接口进行扩展 :

public interface TInterface {    //原有一个sayHello()方法。    void sayHello();}
/** * TImplement 实现了 TInterface接口,并重写了sayHello()方法 * @author Administrator * */public class TImplement implements TInterface {    @Override    public void sayHello() {        // TODO Auto-generated method stub        System.out.println("Hello");    }}
/** * AImplement 也实现了 TInterface接口,但是现在需要在AImplement中新增greeting()方法,并希望在接口中实现 * 而且需要兼容以前的程序,要实现这个功能,解决方案不是单一的,例如可以另写一个接口继承TInterface接口, * 然后AImplement继承新的接口,但Java8中对Interface新增了Default方法,我们可以在不另加其他接口的情 * 况下对原有接口进行扩展 *  * @author Administrator * */public class AImplement implements TInterface {    @Override    public void sayHello() {        // TODO Auto-generated method stub        System.out.println("Say Hello!");    }}

修改原来的TInterface接口 ,新增greeting()方法。

public interface TInterface {    //原有一个sayHello()方法。    void sayHello();    //新增greeting()方法,并编写默认实现代码    default public void greeting(){        System.out.println("Say Greeting");    }}

在AImplement中重写greeting()方法,覆盖默认方法。

/** * AImplement 也实现了 TInterface接口,但是现在需要在AImplement中新增greeting()方法,并希望在接口中实现 * 而且需要兼容以前的程序,要实现这个功能,解决方案不是单一的,例如可以另写一个接口继承TInterface接口,然后AImplement * 继承新的接口,但Java8中对Interface新增了Default方法,我们可以在不另加其他接口的情况下对原有接口进行扩展 *  * @author Administrator * */public class AImplement implements TInterface {    @Override    public void sayHello() {        // TODO Auto-generated method stub        System.out.println("Say Hello!");    }    /*      * 重写greeting()方法,以适应不同的需求     */    @Override    public void greeting() {        // TODO Auto-generated method stub        System.out.println("Override!");    }}

此时我们已经完成在不破坏原有程序的基础之上对接口进行了扩展。

public static void main(String[] args) throws InstantiationException, IllegalAccessException {        AImplement.class.newInstance().greeting();    }

测试输出:Override!


Static Methods
A static method is a method that is associated with the class in which it is defined rather than with any object. Every instance of the class shares its static methods.

Static Methods可以在接口中定义Static方法,并且每一个实例(该接口)都共享这些方法。

/** * static 方法无法override,该接口的每个实例都将共享这个say()方法。 *  * @author Administrator * */public interface TInterface {    // Static Method     static public String say(){        return "123456";    }}

直接使用接口调用该方法

    public static void main(String[] args) {        //使用接口直接调用该方法        System.out.println(TInterface.say());    }

输出结果:123456

0 0