How do you define interfaces in Java?

In Java, an interface can be defined using the interface keyword. It can include abstract methods, default methods, and static methods, but cannot contain instance fields or constructors.

Here is the syntax for defining interfaces:

public interface 接口名 {
    // 抽象方法声明
    void 方法名();

    // 默认方法声明
    default void 默认方法名() {
        // 方法体
    }

    // 静态方法声明
    static void 静态方法名() {
        // 方法体
    }
}

In this case, the interface name is a name you define yourself, which can be named as needed. The abstract methods in the interface do not have a method body, they simply declare the method’s name, parameters, and return type. Default methods and static methods can have a method body and provide default method implementations directly in the interface.

It should be noted that interfaces cannot be instantiated and can only be implemented or extended by other classes. A class implementing an interface needs to use the “implements” keyword, while an interface extending another interface needs to use the “extends” keyword.

Here is an example of defining an interface and implementing it:

public interface Animal {
    void sound();
}

public class Dog implements Animal {
    @Override
    public void sound() {
        System.out.println("汪汪汪!");
    }
}

public class Main {
    public static void main(String[] args) {
        Animal dog = new Dog();
        dog.sound();
    }
}

In the example above, Animal is an interface, and the Dog class implements this interface. The Dog class must implement the sound() method from the Animal interface and provide a specific method implementation. In the main method of the Main class, a Dog object is created and the sound() method is called. The output is “Woof woof woof!”

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds