How do you define an interface in Java?

In Java, the keyword interface is used to define interfaces. Interfaces can include method declarations, but cannot contain method implementations. The syntax for defining an interface is as follows:

public interface 接口名称 {
    // 方法的声明
}

Methods in interfaces are by default public and abstract, and these modifiers can be omitted. Interfaces can be implemented by other classes using the “implements” keyword. Here is an example:

public interface Drawable {
    void draw(); // 声明一个抽象方法
}

public class Circle implements Drawable {
    @Override
    public void draw() {
        System.out.println("Drawing a circle");
    }
}

In the example above, Drawable is an interface that includes an abstract method draw(). The Circle class implements the Drawable interface and implements the draw() method.

bannerAds