溫馨提示×

interface在java中怎么使用

小億
106
2023-08-31 05:07:03
欄目: 編程語言

在Java中,可以使用關(guān)鍵字"interface"來定義一個接口。接口是一種抽象類型,它只定義了方法的簽名和常量的聲明,而沒有具體實現(xiàn)。

以下是定義一個接口的基本語法:

public interface 接口名稱 {
// 聲明常量
// 聲明方法
}

接口中的常量和方法默認(rèn)為公共的,無需添加訪問修飾符。一個類可以實現(xiàn)(implement)一個或多個接口,實現(xiàn)接口的類需要實現(xiàn)接口中聲明的所有方法。

以下是一個簡單的示例,展示了如何定義和實現(xiàn)接口:

// 定義一個接口
public interface Animal {
int LEGS = 4; // 接口中的常量
void makeSound(); // 接口中的方法
}
// 實現(xiàn)接口
public class Dog implements Animal {
@Override
public void makeSound() {
System.out.println("汪汪!");
}
}
public class Main {
public static void main(String[] args) {
Dog dog = new Dog();
dog.makeSound(); // 輸出:"汪汪!"
System.out.println(Animal.LEGS); // 輸出:4
}
}

在以上示例中,Animal是一個接口,其中聲明了一個常量LEGS和一個方法makeSound。Dog類實現(xiàn)了Animal接口,并實現(xiàn)了makeSound方法。在Main類中,我們創(chuàng)建了一個Dog對象并調(diào)用了makeSound方法和訪問了Animal接口中的常量LEGS。

0