java中interface关键字怎么调用

   2025-02-15 6570
核心提示:在Java中,interface关键字用来定义一个接口,不可以直接调用接口,而是需要通过实现该接口的类来调用。首先,创建一个接口:pub

在Java中,interface关键字用来定义一个接口,不可以直接调用接口,而是需要通过实现该接口的类来调用。

首先,创建一个接口:

public interface MyInterface {    void myMethod();}

然后,创建一个类来实现该接口:

public class MyClass implements MyInterface {    @Override    public void myMethod() {        System.out.println("调用了接口的方法");    }}

最后,在其他地方调用实现类的方法:

public class Main {    public static void main(String[] args) {        MyClass myObj = new MyClass();        myObj.myMethod();    }}

这样,就可以通过实现类来调用接口中定义的方法。

 
 
更多>同类维修知识
推荐图文
推荐维修知识
点击排行
网站首页  |  关于我们  |  联系方式  |  用户协议  |  隐私政策  |  网站留言