更新時間:2022-08-22 11:52:07 來源:動力節點 瀏覽1737次
在 Java 中,接口是一種類似于類的引用類型,它只能包含常量、方法簽名、默認方法和靜態方法,以及 ts 嵌套類型。在接口中,方法體只存在于默認方法和靜態方法中。編寫接口類似于編寫標準類。不過,類描述屬性和內部行為對象,接口包含類實現的行為。另一方面,除非實現接口的類是純抽象的,并且所有接口方法都需要在給定的可用類中定義。
一個接口可以在該接口中包含任意數量的方法。
接口名稱寫在帶有 –(.java 擴展名)的文件中,接口名稱必須與該 Java 程序的文件名稱匹配。
給定接口的字節碼將在 – .class 文件中創建。
接口出現在包中,它們對應的字節碼文件必須同樣位于與包名匹配的結構中。
interface 關鍵字用于聲明接口。這里我們有一個聲明接口的簡單例子。
public interface NameOfTheinterface
{
// Any final, static fields here
// Any abstract method declaration here
}
//This is Declaration of the interface
接口具有以下屬性:
接口是隱含的純抽象。
聲明接口時不需要使用 abstract 關鍵字
接口中的每個方法也是隱式抽象的,所以不需要 abstract 關鍵字
接口中的方法在其中隱式公開
示例:文件名 – Car.java
// This is Program To implement the Interface
interface car
{
void display();
}
class model implements car
{
public void display()
{
System.out.println("im a Car");
// the code output will print "im a car"
}
public static void main(String args[])
{
model obj = new model();
obj.display();
}
}
輸出
我是一輛車
功能接口
標記界面
1.功能接口:
功能接口是只有一個純抽象方法的接口。
它可以有任意數量的靜態和默認方法,甚至還有java.lang.Object類的公共方法
當一個接口只包含一個抽象方法時,它被稱為功能接口。
功能接口示例:
Runnable : 它只包含 run() 方法
ActionListener : 它只包含 actionPerformed()
ItemListener : 它只包含 itemStateChanged() 方法
現在我們將看到一個功能接口的示例——
例子:
// This is Program To implement the Functional Interface
interface Writable
{
void write(String txt);
}
// FuninterExp is a Example of Functional Interface
public class FuninterExp implements Writable
{
public void write(String txt)
{
System.out.println(txt);
}
public static void main(String[] args)
{
FuninterExp obj = new FuninterExp();
obj.write(" GFG - GEEKS FOR GEEKS ");
}
}
輸出
GFG - 極客的極客
2. 標記界面:
不包含任何方法、字段、抽象方法和任何常量的Java接口稱為標記接口。
此外,如果接口為空,則稱為標記接口。
Serializable 和 Cloneable 接口是 Marker 接口的示例。
例如:
// Simple Example to understand marker interface
public interface interface_name
{
// empty
}
0基礎 0學費 15天面授
有基礎 直達就業
業余時間 高薪轉行
工作1~3年,加薪神器
工作3~5年,晉升架構
提交申請后,顧問老師會電話與您溝通安排學習