1. 程式人生 > >JAVA中接口的使用

JAVA中接口的使用

ace interface sum esc 部分 anim 權限 main nbsp

  抽象類是從多個類中抽象出來的模板,如果將這種抽象進行的更徹底,那麽就是接口(interface)了。什麽是接口,簡單的講,接口就是抽象類的進一步抽象,這種進一步的抽象只定義了一種規範,而不需要關心具體的數據狀態和方法實現細節,它只規定了一部分必須提供的方法。下面介紹接口的具體使用細節;

  1.接口裏不能包含構造器和初始化塊定義,只能包含成員變量(靜態常量)、方法(抽象實例方法、類方法或默認方法)、內部類(內部接口、枚舉)這三種成員。

  2.接口裏的所有成員都應該定義為public權限,這個public可以省略,系統會自動補充。同理,接口裏定義的靜態常量會自動增加static和final,因此也可以省略。而且由於沒有構造器和初始化塊,接口裏面的成員變量只能在定義時指定初始值。

  3.接口裏定義的方法只能是抽象方法、類方法或默認方法,所以系統會自動為普通方法增加public abstract修飾,同時普通方法不能有方法體(抽象方法)。但是類方法和默認方法都必須要有方法體。

  4.默認方法必須要有default修飾,不能用static修飾,同理public會自動增加,默認方法需要接口實現的類的實例來調用。類方法必須要static修飾,public自動增加,類方法可以用接口來直接調用。

  5.接口支持多繼承,即一個接口可以有多個直接父接口。

  下面是具體的例子:

package biology;
public interface Animal
{
    
int classification = 7; String eat(); String move(); default void description() { System.out.println("I am a kind of biology"); } static String summary() { return "The nature is wonderful"; } } package biology; public class Dog implements Animal {
public String name; public Dog(String name) { this.name = name; } public String eat() { return name + " eat meat and grass"; } public String move() { return name + " move with dog‘s legs"; } } package biology; public class Goat implements Animal { public String name; public Goat(String name) { this.name = name; } public String eat() { return name + " eat grass"; } public String move() { return name + " move with goat‘s legs"; } } package biology; public class Tiger implements Animal { public String name; public Tiger(String name) { this.name = name; } public String eat() { return name + " eat meat"; } public String move() { return name + " move with tiger‘s legs"; } } package biology; public class Test { public static void main(String[] args) { Dog animal1 = new Dog("Shepherd"); Tiger animal2 = new Tiger("Bengal Tiger"); Goat animal3 = new Goat("sheep"); System.out.println("The classification of biology is " + Animal.classification); System.out.println(animal1.name + ": " + animal1.eat() + ". " + animal1.move()); System.out.println(animal2.name + ": " + animal2.eat() + ". " + animal2.move()); System.out.println(animal3.name + ": " + animal3.eat() + ". " + animal3.move()); animal1.description(); animal2.description(); animal3.description(); System.out.println(Animal.summary()); } }

  運行結果如下:

The classification of biology is 7
Shepherd: Shepherd eat meat and grass. Shepherd move with dogs legs
Bengal Tiger: Bengal Tiger eat meat. Bengal Tiger move with tigers legs
sheep: sheep eat grass. sheep move with goats legs
I am a kind of biology
I am a kind of biology
I am a kind of biology
The nature is wonderful

  在這裏例子中,我們定義了一個接口Animal, 在這個接口中定義了一個成員變量classification(自動添加public static final 修飾, 由接口調用),兩個抽象方法eat()和move()(自動添加public abstract 修飾, 由接口實現類來實現), 一個默認方法(由接口實現類的實例調用),一個類方法(直接由接口調用)。

  差不多就是這麽多,具體的細節還要多看書和敲代碼。

JAVA中接口的使用