How to add an interface in a class in Java?

To add an interface in a class, you need to follow these steps:

  1. – connection point
public interface MyInterface {
    void myMethod();
}
  1. tools or equipment
public class MyClass implements MyInterface {
    @Override
    public void myMethod() {
        // 实现接口方法的具体逻辑
    }
}
  1. Utilize interfaces: create objects of a class and invoke methods in the interface.
public class Main {
    public static void main(String[] args) {
        MyClass myObj = new MyClass();
        myObj.myMethod(); // 调用接口方法
    }
}

In this way, by implementing an interface in a class, we can leverage the polymorphism of the interface to achieve flexibility and scalability of the class.

bannerAds