更新時(shí)間:2022-09-20 10:48:32 來(lái)源:動(dòng)力節(jié)點(diǎn) 瀏覽3192次
Java怎樣定義接口的關(guān)鍵字?動(dòng)力節(jié)點(diǎn)小編來(lái)為大家舉例說明。
Aninterface是一個(gè)抽象“類”,用于將相關(guān)方法與“空”主體分組:
要訪問Java接口方法,接口必須由另一個(gè)使用implements 關(guān)鍵字(而不是)的類“實(shí)現(xiàn)”(有點(diǎn)像繼承extends)。接口方法的主體由“實(shí)現(xiàn)”類提供:
// interface
interface Animal {
public void animalSound(); // interface method (does not have a body)
public void sleep(); // interface method (does not have a body)
}
// Pig "implements" the Animal interface
class Pig implements Animal {
public void animalSound() {
// The body of animalSound() is provided here
System.out.println("The pig says: wee wee");
}
public void sleep() {
// The body of sleep() is provided here
System.out.println("Zzz");
}
}
class MyMainClass {
public static void main(String[] args) {
Pig myPig = new Pig(); // Create a Pig object
myPig.animalSound();
myPig.sleep();
}
}
interface關(guān)鍵字用于聲明只包含抽象方法的特殊類型的類。
要訪問接口方法,接口必須由另一個(gè)使用implements 關(guān)鍵字(而不是)的類“實(shí)現(xiàn)”(有點(diǎn)像繼承extends)。接口方法的主體由“實(shí)現(xiàn)”類提供。
要實(shí)現(xiàn)多個(gè)接口,請(qǐng)用逗號(hào)分隔它們:
interface FirstInterface {
public void myMethod(); // interface method
}
interface SecondInterface {
public void myOtherMethod(); // interface method
}
// DemoClass "implements" FirstInterface and SecondInterface
class DemoClass implements FirstInterface, SecondInterface {
public void myMethod() {
System.out.println("Some text..");
}
public void myOtherMethod() {
System.out.println("Some other text...");
}
}
class MyMainClass {
public static void main(String[] args) {
DemoClass myObj = new DemoClass();
myObj.myMethod();
myObj.myOtherMethod();
}
}
以上就是關(guān)于“Java定義接口的關(guān)鍵字”的介紹,大家如果想了解更多相關(guān)知識(shí),不妨來(lái)關(guān)注一下動(dòng)力節(jié)點(diǎn)的Java在線學(xué)習(xí),里面的課程內(nèi)容細(xì)致全面,適合沒有基礎(chǔ)的小伙伴學(xué)習(xí),相信對(duì)大家一定會(huì)有所幫助的哦。
相關(guān)閱讀
Java實(shí)驗(yàn)班
0基礎(chǔ) 0學(xué)費(fèi) 15天面授
Java就業(yè)班
有基礎(chǔ) 直達(dá)就業(yè)
Java夜校直播班
業(yè)余時(shí)間 高薪轉(zhuǎn)行
Java在職加薪班
工作1~3年,加薪神器
Java架構(gòu)師班
工作3~5年,晉升架構(gòu)
提交申請(qǐng)后,顧問老師會(huì)電話與您溝通安排學(xué)習(xí)