Java提供的這個interface的語法,目的就是將接口從類中剝離出來,構成獨立的主體。java
首先加入咱們定義了這個杯子接口c++
interface Cup { void addWater(int w); void drinkWater(int w); }
interface當中,注意亮點:ide
1.不須要定義方法的主體spa
2.不須要說明的可見性(默認爲public)orm
在一個的類中實施接口,例以下面的MusicCup對象
class MusicCup implements Cup { public void addWater(int w) { water = water + w; } public void drinkWater(int w) { water = water - w; } private int water = 0; }
這裏須要注意的就是:一旦在類中實施了某個interface,必須在該類中定義interface的全部方法(addWater()和drinkWater())。類中的方法須要與interface中的方法原型相符。不然,Java將報錯。接口
interface接口存在的意義:ci
咱們使用了interface,但這個interface並無減小咱們定義類時的工做量。咱們依然要像以前同樣,具體的編寫類。咱們甚至於要更加當心,原型
不能違反了interface的規定。既然如此,咱們爲何要使用interface呢?源碼
事實上,interface就像是行業標準。一個工廠(類)能夠採納行業標準 (implement interface),也能夠不採納行業標準。
可是,一個採納了行業標準的產品將有下面的好處:
更高質量: 沒有加水功能的杯子不符合標準。
更容易推廣: 正如電腦上的USB接口同樣,下游產品能夠更容易銜接。
若是咱們已經有一個Java程序,用於處理符合Cup接口的對象,好比領小朋友喝水。那麼,只要咱們肯定,咱們給小朋友的杯子(對象)實施了Cup接口,就能夠確保小朋友能夠執行喝水這個動做了。
至於這個杯子(對象)是如何具體定義喝水這個動做的,咱們就能夠留給相應的類自行決定 (好比用吸管喝水,或者開一個小口喝水)。
多個接口:
一個類能夠實施不止一個接口interface。
例如咱們還有一個interface:
interface Musicplayer { void play(); }
因此真正的MusicCup還須要實施這個接口,因此以下所示:
class MusicCup implements Cup, MusicPlayer { public void addWater(int w) { water = water + w; } public void drinkWater(int w) { water = water - w; } public void play() { System.out.println("dun...dun...dun..."); } private int water = 0; }
就這些,好了附帶一個源碼你們看吧:
interface Cup { void addWater(int w); void drinkWater(int w); } interface MusicPlayer { void play(); } /*這個類若是implements Cup了,那麼Cup中定義的方法, 在MusicCup 中必需要有addWater和drinkWater,不然會報錯,這點和c++不同*/ class MusicCup implements Cup, MusicPlayer { public void addWater(int w) { water = water + w; System.out.println("water is " + water); } public void drinkWater(int w) { water = water - w; System.out.println("water is " + water); } public void play() { for (int i = 0; i <water; i++) { System.out.println("dun...dun...dun..."); } } public int waterContent() { return water; } private int water = 0; } public class test { public static void main(String[] args) { MusicCup mycupCup = new MusicCup(); mycupCup.addWater(5); mycupCup.play(); mycupCup.drinkWater(3); mycupCup.play(); System.out.println("water content is " + mycupCup.waterContent()); } }
輸出結果:
water is 5dun...dun...dun...dun...dun...dun...dun...dun...dun...dun...dun...dun...dun...dun...dun...water is 2dun...dun...dun...dun...dun...dun...water content is 2