[Java] java中的接口定义
在Java的通常規(guī)范中,對(duì)數(shù)據(jù)成員的修改要通過(guò)接口提供的方法進(jìn)行(如下面示例中接口中的void learnMath(int hours)和void learnEnglish(int hours)),這個(gè)規(guī)范起到了保護(hù)數(shù)據(jù)的作用。用戶不能直接修改數(shù)據(jù),必須通過(guò)相應(yīng)的方法才能讀取和寫(xiě)入數(shù)據(jù)。類(lèi)的設(shè)計(jì)者可以在接口方法中加入數(shù)據(jù)的使用規(guī)范。
在interface中,我們
- 不需要定義方法的主體
- 不需要說(shuō)明方法的可見(jiàn)性
一個(gè)類(lèi)的public方法構(gòu)成了接口,所以interface中的方法默認(rèn)為public。我們用implements關(guān)鍵字來(lái)實(shí)施interface。一旦在類(lèi)中實(shí)施了某個(gè)interface,必須在該類(lèi)中定義interface的所有方法(learnMath(int hours)和?learnEnglish(int hours))。類(lèi)中的方法需要與interface中的方法原型相符。否則,Java將報(bào)錯(cuò)。
另外,一個(gè)類(lèi)可以實(shí)施不止一個(gè)的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 }?
轉(zhuǎn)載于:https://www.cnblogs.com/frost-yen/p/4755333.html
總結(jié)
以上是生活随笔為你收集整理的[Java] java中的接口定义的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: iOS基础-高级视图-UITableVi
- 下一篇: ubuntu 14.04 安装Java