How to define an interface in Java?

In Java, interfaces can be defined using the keyword ‘interface’. Interfaces can contain constants and abstract methods, but cannot contain instance variables or non-abstract methods.

Below is the syntax for defining an interface:

public interface 接口名 {
    // 常量声明
    // 抽象方法声明
}

In an interface, you can declare constants and abstract methods, but you cannot have a method body. Constants in an interface are by default public static final, while abstract methods are by default public abstract.

For example, define an interface named Animal that contains a constant and an abstract method:

public interface Animal {
    int LEGS = 4; // 常量声明

    void sound(); // 抽象方法声明
}

In addition, interfaces can also inherit other interfaces using the keyword “extends”, and can inherit multiple interfaces at the same time. The syntax is as follows:

public interface 子接口名 extends 父接口名1, 父接口名2, ... {
    // 常量声明
    // 抽象方法声明
}

For example, create an interface named Walkable that extends the Animal interface.

public interface Walkable extends Animal {
    void walk();
}

Classes can implement interfaces using the “implements” keyword. A class can implement multiple interfaces, but must implement all abstract methods in the interface. The syntax is as follows:

public class 类名 implements 接口名1, 接口名2, ... {
    // 类的实现
}

For example, define a class named Dog that implements the Animal interface and the Walkable interface.

public class Dog implements Animal, Walkable {
    public void sound() {
        System.out.println("汪汪");
    }

    public void walk() {
        System.out.println("四条腿走路");
    }
}

In this way, the Dog class has implemented all the abstract methods in the Animal interface and the Walkable interface.

bannerAds