class Refrigerator implements Power{
public void getPowerFromTP(){
System.out.println("轉換..轉換....")
}
}
Power obj = new Refrigerator();
obj.getPowerFromTP();
轉換..轉換....
class 類別名稱 implements 介面1,介面2,...介面n{
// 成員定義
}
interface A{
void Amethod();
}
interface B{
void Bmethod();
}
class MyClass implements A,B {
public void Amethod(){
}
public void Bmethod(){
}
}
public abstract 回傳型態 方法名稱();
interface MyInterface{
public abstract void A(); // ok
public void B(); // ok,編譯完會自行在執行檔加上 public abstract
void C(); // ok,編譯完會自行在執行檔加上 public abstract
private void D(); // no ok, 編譯錯誤,修飾子不正確
void E(){}; // no ok, 編譯錯誤,只能定義原型,不行定義方法本體
}
public static final 資料型態 變數名稱 = 值;
interface Qoo{
int value = 10;
public int value2 = 20;
public static int value3 = 30;
public static final int value4 = 40;
// 以上四行敘述,編譯完成後在執行檔中修飾子均為 public static final
int value5; // 編譯錯誤,必須給訂初始值
private int value6 = 60; // 編譯錯誤,private與public衝突
}
介面名稱.欄位名稱;
interface Power{
int value = 10;
}
class Test{
public static void main(String[] args){
System.out.println(Power.value);
}
}
10
interface Inter1 {
int value = 10;
}
interface Inter2 {
int value = 20;
}
class Father{
int value = 30;
}
class A extends Father implements Inter1,Inter2{
int value = 40;
}
class Test {
public static void main(String[] args) {
A a = new A();
System.out.println( Inter1.value ); // 以介面名稱存取,因為是static修飾
System.out.println( Inter2.value ); // 同上
System.out.println( ((Father)a).value ); // 先把物件a轉型成該父類別,再存取
System.out.println( a.value ); // 直接以物件存取
}// end of main(String[])
}// end of class Test
10
20
30
40
interface A{
void method();
}
interface B{
void method();
int method(int a);
}
class MyClass implements A,B{
public int method(int a) {
//...
}
public void method() {
//...
}
}
interface 介面名稱 extends 介面1,介面2,...,介面n{
}
interface A{
void a();
}
interface B{
void b();
}
interface C extends A,B{ // 介面的繼承,繼承多個介面以逗號『,』隔開
void c();
}
class MyClass implements C{ // 必須實作介面C及其所有父類別定義的方法
public void a() {
}
public void b() {
}
public void c() {
}
}
interface A{
void a();
void b();
}
abstract class AbsClass implements A{
public void b(){
System.out.println("hello b~");
}
abstract void c();
}
class MyClass extends AbsClass{
public void a() {
}
// 方法b()已經在AbsClass實作,MyClass不需要再實作,當然也可以再覆寫b()
public void c() {
}
}