[問題] interface系統產生問題

作者: APE36 (PT鄉民)   2014-07-22 14:50:47
public class Interface1{
public static void main(String[] args) {
Bird b = new Bird();
b.canFly();
System.out.println(b.name);
/***從這裡開始以下四行,不知道為何能跑出Answer的結果
Actions a = new Airplane();
a.canFly();
System.out.println(a.name); //資料成員用的是Actions中的name
//System.out.println(a.price); //這行會產生錯誤,不能用Airplane中定義的成員
} ***/
}
interface Actions { //介面的宣告
public String name = "Some Actions";
public void canFly(); //定義方法
public void canRun(); //定義方法
}
class Bird implements Actions{ //Bird類別實作介面
public String name = "Bird";
public void canFly(){
System.out.println("Bird Flying...");
}
public void canRun() {} //這樣也算實作了
}
class Airplane implements Actions{ //Airplane類別實作介面
public String name = "Airplane";
public int price =100;
public void canFly(){ //一定要實作介面中的方法
System.out.println("Airplane Flying...");
}
public void canRun() {}; //這樣也算實作了
}
ANSWER:
Bird Flying...
Bird
Airplane Flying...
Some Actions
麻煩版上大大的指導!!感謝
作者: PttTime   2014-07-22 21:15:00
Actions沒有price member當然不能a.price故a.name為Some Actions也不足為奇interface裡的變數會自動變成static變數

Links booklink

Contact Us: admin [ a t ] ucptt.com