Strengthen the new features of Java interfaces

Strengthen the interface

Before JDK1.8 interface definition:

  • Interface is a collection of abstract methods and go global constants;
  • The method defined in the interface is an abstract method, default public abstractmodification;
  • Variables defined in the interface, in fact, is a constant, and is public static finalmodified.

If there is now a need, we need to add a new interface features, and its subclasses have 3Wone, then they would repeat the paste 3Wtimes.
The cause of the problem is: just because the interface declares a method , but no specific implementation, so as time goes on, the interface can not be used .

In order to solve the above problems, specifically provides two new structures.
After JDK1.8 interface definition:

  • Used defaultto define the conventional method, call through the object;
  • Use staticto define static methods can be called by the name of the interface.

For example: define a general method

public interface Message {
    void print();
    /**
     * 如果增加一个greeting方法,那么子类都要实现它,否则都会报错,
     * 如果子类数量相当多,那么实现起来很困难,因此引入了默认方法。
     */
    //追加了普通方法,必须有方法体
    default void greeting(){
        System.out.println("default greeting!");
    }

}

public class QQMessage implements Message{
    @Override
    public void print() {
        System.out.println("print QQMessage!");
    }
}

public class WeiXinMessage implements Message{
    @Override
    public void print() {
        System.out.println("print WeiXinMessage!");
    }
}

public class TestMessage {
    public static void main(String[] args) {
        //此处也可以写成QQMessage的对象调用greeting方法,
        //类似继承,它是一个普通方法,将它继承下来。
        Message qq = new QQMessage();
        qq.print();
        qq.greeting();
    }
}

If not satisfied with the method of the parent class, subclass may be overwritten based on the actual situation . Then the parent object is called a subclass ordinary method override.
Example: static method defined

public interface Message {
    void print();
    
    default void greeting(){
        System.out.println("default greeting!");
    }

    //可以直接通过接口名称调用 Message.messageInfo()
    static void messageInfo(){
        System.out.println("static 方法");
    }
}

Overall speaking, the interface feels more like an abstract class, but more powerful than abstract classes are: sub-class interface can inherit multiple parent interfaces and abstract classes is to achieve single inheritance .

Guess you like

Origin blog.csdn.net/mi_zhi_lu/article/details/91359147