Java Coding 編程系列: 初級篇之六: Interface 介面概念
Java Coding 編程系列: 初級篇之六: Interface 介面概念
Java不允許多重繼承,即是任何類別只能有一個父類別。
如果遇到需要多重繼承的情況,就可以用Interface 介面的形式:
假設 class --> fruit -->apple
class -> fruit --> orange
如果寫成:
class fruit extends apple, orange {
}
是錯的。
用 Interface 介面 加上implements 兩個關鍵字,改成:
class fruit extends apple implements orange {
}
這樣就可以了
Interface 的變數Default 是static 和final。為什麼呢?
Interface 的變數是static靜態的,因為 Java 不能單獨實例化;變數的值必須在不存在實例的靜態static 中分配。final修飾符確保分配給變數的值是一個真正的常數,程序代碼不能重新分配並變更。
例子:
interface typing{
void type();
}
class typenew
implements typing{
public void
print(){System.out.println("Typing in computer.");}
public
static void main(String args[]){
typenew obj
= new typenew();
obj.print();
}
}
留言
張貼留言