java中interface怎样调用
在Java中,接口(interface)本身不能被实例化,也不能直接调用方法。但是,接口可以被其他类实现(implement),而实现类可以通过实现接口的方式,来调用接口中的方法。
具体的步骤以下:
public interface MyInterface {
void myMethod();
}
public class MyClass implements MyInterface {
public void myMethod() {
System.out.println("调用了myMethod方法");
}
}
public class MainClass {
public static void main(String[] args) {
MyInterface obj = new MyClass();
obj.myMethod();
}
}
上述代码中,创建了一个实现类 MyClass,实现了接口 MyInterface 中的 myMethod 方法。然后,在 MainClass 类的 main 方法中,通过实例化 MyClass 对象,并将其赋值给接口类型的变量 obj,然后可以通过 obj 调用接口中的方法 myMethod。
输出结果为:“调用了myMethod方法”。
TOP