更新時(shí)間:2022-08-22 11:52:07 來源:動(dòng)力節(jié)點(diǎn) 瀏覽1815次
在 Java 中,接口是一種類似于類的引用類型,它只能包含常量、方法簽名、默認(rèn)方法和靜態(tài)方法,以及 ts 嵌套類型。在接口中,方法體只存在于默認(rèn)方法和靜態(tài)方法中。編寫接口類似于編寫標(biāo)準(zhǔn)類。不過,類描述屬性和內(nèi)部行為對(duì)象,接口包含類實(shí)現(xiàn)的行為。另一方面,除非實(shí)現(xiàn)接口的類是純抽象的,并且所有接口方法都需要在給定的可用類中定義。
一個(gè)接口可以在該接口中包含任意數(shù)量的方法。
接口名稱寫在帶有 –(.java 擴(kuò)展名)的文件中,接口名稱必須與該 Java 程序的文件名稱匹配。
給定接口的字節(jié)碼將在 – .class 文件中創(chuàng)建。
接口出現(xiàn)在包中,它們對(duì)應(yīng)的字節(jié)碼文件必須同樣位于與包名匹配的結(jié)構(gòu)中。
interface 關(guān)鍵字用于聲明接口。這里我們有一個(gè)聲明接口的簡(jiǎn)單例子。
public interface NameOfTheinterface
{
// Any final, static fields here
// Any abstract method declaration here
}
//This is Declaration of the interface
接口具有以下屬性:
接口是隱含的純抽象。
聲明接口時(shí)不需要使用 abstract 關(guān)鍵字
接口中的每個(gè)方法也是隱式抽象的,所以不需要 abstract 關(guān)鍵字
接口中的方法在其中隱式公開
示例:文件名 – 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();
}
}
輸出
我是一輛車
功能接口
標(biāo)記界面
1.功能接口:
功能接口是只有一個(gè)純抽象方法的接口。
它可以有任意數(shù)量的靜態(tài)和默認(rèn)方法,甚至還有java.lang.Object類的公共方法
當(dāng)一個(gè)接口只包含一個(gè)抽象方法時(shí),它被稱為功能接口。
功能接口示例:
Runnable : 它只包含 run() 方法
ActionListener : 它只包含 actionPerformed()
ItemListener : 它只包含 itemStateChanged() 方法
現(xiàn)在我們將看到一個(gè)功能接口的示例——
例子:
// 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. 標(biāo)記界面:
不包含任何方法、字段、抽象方法和任何常量的Java接口稱為標(biāo)記接口。
此外,如果接口為空,則稱為標(biāo)記接口。
Serializable 和 Cloneable 接口是 Marker 接口的示例。
例如:
// Simple Example to understand marker interface
public interface interface_name
{
// empty
}
相關(guān)閱讀
0基礎(chǔ) 0學(xué)費(fèi) 15天面授
有基礎(chǔ) 直達(dá)就業(yè)
業(yè)余時(shí)間 高薪轉(zhuǎn)行
工作1~3年,加薪神器
工作3~5年,晉升架構(gòu)
提交申請(qǐng)后,顧問老師會(huì)電話與您溝通安排學(xué)習(xí)
初級(jí) 202925
初級(jí) 203221
初級(jí) 202629
初級(jí) 203743