21xrx.com
2025-03-21 09:01:51 Friday
文章检索 我的文章 写文章
Java的接口创建及使用
2023-06-17 13:22:44 深夜i     9     0
Java接口 方法 常量

在Java中,接口是一种与类类似但又有所不同的结构。接口没有具体的实现,只有方法的定义,这些方法必须由实现该接口的类提供具体的实现。接口使用关键字“interface”来声明,如下所示:

public interface MyInterface {
  public void method1();
  public void method2();
}

可以看出,接口中定义了两个方法method1和method2,但并没有实现它们。我们可以用下面的语句来实现该接口:

public class MyClass implements MyInterface {
  public void method1() {
    System.out.println("Method 1 implementation");
  }
  public void method2() {
    System.out.println("Method 2 implementation");
  }
}

可以看出,MyClass类实现了MyInterface接口中定义的所有方法。除了实现接口中定义的方法外,我们还可以给接口添加属性,如下所示:

public interface MyInterface {
  int MAX = 100;
  public void method1();
  public void method2();
}

可以看出,我们在接口中定义了一个常量MAX,MyClass中可以像下面的代码一样使用该常量:

public class MyClass implements MyInterface {
  public void method1() {
    System.out.println("Method 1 implementation");
  }
  public void method2() {
    System.out.println("Method 2 implementation");
  }
  public void printMax() {
    System.out.println("The maximum number is " + MyInterface.MAX);
  }
}

当我们需要在类中使用接口时,可以将接口类型作为该类中成员变量的类型,如下所示:

public class MyClass {
  private MyInterface myObj;
  public MyClass(MyInterface myObj)
    this.myObj = myObj;
  
  public void doSomething() {
    myObj.method1();
    myObj.method2();
  }
}

可以看出,在MyClass类的constructor中,我们传入了一个MyInterface类型的参数,在doSomething方法中,我们调用了MyInterface中的方法,而实际上该方法在MyClass和其他的实现了该接口的类中都可以使用。

  
  

评论区