[Java] java中的接口定义

在Java的通常规范中,对数据成员的修改要通过接口提供的方法进行(如下面示例中接口中的void learnMath(int hours)和void learnEnglish(int hours)),这个规范起到了保护数据的作用。用户不能直接修改数据,必须通过相应的方法才能读取和写入数据。类的设计者可以在接口方法中加入数据的使用规范。

在interface中,我们

  • 不需要定义方法的主体
  • 不需要说明方法的可见性

一个类的public方法构成了接口,所以interface中的方法默认为public。我们用implements关键字来实施interface。一旦在类中实施了某个interface,必须在该类中定义interface的所有方法(learnMath(int hours)和 learnEnglish(int hours))。类中的方法需要与interface中的方法原型相符。否则,Java将报错。

另外,一个类可以实施不止一个的interface。

 1 public class Test{
 2     public static void main(String[] args){
 3         LearnCourse learnCourse = new LearnCourse(3);
 4         learnCourse.learnMath(2);
 5         learnCourse.learnEnglish(4);
 6     }
 7 }
 8 class LearnCourse implements Learn{
 9     LearnCourse(int t){
10 
11     }
12     public void learnMath(int hours){
13         this.timeMath = hours;
14         System.out.println("The time for Learning Math is "+hours+" hours");
15     }
16     public void learnEnglish(int hours){
17         this.timeEnglish = hours;
18         System.out.println("The time for Learning English is "+hours+" hours");
19     }
20     private int timeMath = 0;
21     private int timeEnglish = 0;
22 }
23 interface Learn{
24     void learnMath(int hours);
25     void learnEnglish(int hours);
26 }
原文地址:https://www.cnblogs.com/frost-yen/p/4755333.html