How to invoke a Java interface
In Java, an interface is a protocol or contract that defines what methods a class must follow, without including the implementation. To invoke an interface, you can follow these steps:
- Create a class that implements an interface.
- Implement the methods declared in the interface in the implementing class.
- Create a reference variable for an interface and initialize it with an object of the implementing class.
- Use interface reference variables to call methods declared in the interface.
Here is a simple example code:
// 定义一个接口
interface MyInterface {
void myMethod();
}
// 实现接口
class MyImplementation implements MyInterface {
public void myMethod() {
System.out.println("调用了接口中的方法");
}
}
public class Main {
public static void main(String[] args) {
// 创建接口引用变量,并将其初始化为实现类的对象
MyInterface obj = new MyImplementation();
// 调用接口中的方法
obj.myMethod();
}
}
Running the above code will output “Calling the method in the interface”.