Java on the use of interfaces

  1. Interface is defined using interface
  2. In Java, interfaces and classes are two parallel structures
  3. How to define an interface: define the members in the interface
    • JDK7 and before: Only global constants and abstract methods can be defined. Global constants
      : public static final. But when writing code, you can omit it. The default is public static final
      abstract method: public abstract. But when writing code, you can omit Do not write, the default is public abstract
    • JDK8: In addition to defining global constants and abstract methods, you can also define static methods and default methods
interface Person{
    
    
    //可以省略不写,默认为public static final的
    public static final String name = "Mr.Yu";
    //省略了public static final
    int age = 21;

    //可以省略不写,默认为public abstract的
    public abstract void walk();
    //省略了public abstract
    void eat();


    //JDK8:除了定义全局常量和抽象方法之外,还可以定义静态方法、默认方法
    //静态方法
    public static void sleep(){
    
    
        System.out.println("到夜晚了,关灯睡觉!");
    }
    //默认方法
    public default void drinkWater(){
    
    
        System.out.println("口渴了,喝点水!");
    }
}
  1. The constructor cannot be defined in the interface! Means that the interface cannot be instantiated

  2. In Java development, the interface is used by letting the class implement (implements).
    If the implementation class covers all the abstract methods in the interface, the implementation class can be instantiated.
    If the implementation class does not cover all the abstract methods in the interface, Then this implementation class is still an abstract class

  3. Java classes can implement multiple interfaces —> make up for the limitations of Java single inheritance
    Format: class AA extends BB implements CC, DD, EE

  4. Interface and interface can be inherited, and multiple inheritance

  5. The specific use of the interface reflects polymorphism

  6. Interface, can actually be regarded as a kind of specification

Guess you like

Origin blog.csdn.net/MrYushiwen/article/details/109776827