更新時間:2022-09-20 10:48:32 來源:動力節點 瀏覽2578次
Java怎樣定義接口的關鍵字?動力節點小編來為大家舉例說明。
Aninterface是一個抽象“類”,用于將相關方法與“空”主體分組:
要訪問Java接口方法,接口必須由另一個使用implements 關鍵字(而不是)的類“實現”(有點像繼承extends)。接口方法的主體由“實現”類提供:
// 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關鍵字用于聲明只包含抽象方法的特殊類型的類。
要訪問接口方法,接口必須由另一個使用implements 關鍵字(而不是)的類“實現”(有點像繼承extends)。接口方法的主體由“實現”類提供。
要實現多個接口,請用逗號分隔它們:
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();
}
}
以上就是關于“Java定義接口的關鍵字”的介紹,大家如果想了解更多相關知識,不妨來關注一下動力節點的Java在線學習,里面的課程內容細致全面,適合沒有基礎的小伙伴學習,相信對大家一定會有所幫助的哦。
0基礎 0學費 15天面授
有基礎 直達就業
業余時間 高薪轉行
工作1~3年,加薪神器
工作3~5年,晉升架構
提交申請后,顧問老師會電話與您溝通安排學習