[問題] interface系統產生問題

看板java作者 (PT鄉民)時間11年前 (2014/07/22 14:50), 編輯推噓2(201)
留言3則, 1人參與, 最新討論串1/1
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 麻煩版上大大的指導!!感謝 -- ◢ ◣ ▊ ▊ ▊ ▊ ◢◣ ◢◣ ▊ ▊ ▊███ ◣ ◣ ◢█ L I N ◣ ▊ ▊ █◣ ▊◢ ◥◣ ▊ ▊ █◣ ▊ ▊ ▊ ▊ ▊ ◥◤ ▊ ▇▇ ◥◤ ▊ ▊ ▊◥◣▊◥ ▊ ▊▊◥◣▊ ▊ ▊ ▊ ▊ ▊ ▊ ▊ ▊ ▊ ◥▊ ◥◣ ▊ ▊▊ ◥▊ ▊ ▊ ▉ ▉ ▊ ▊ ▊ ▊ ◥◣█▆▆▊▊ ▊ ▊ ▊ ◥█ ψ █▇▇ ▊ ▊ ▊◣▅▇◤▊ ▊▊ ▊ ▊ ▊ ▊ -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 114.39.11.48 ※ 文章網址: http://www.ptt.cc/bbs/java/M.1406011850.A.FAD.html

07/22 21:15, , 1F
Actions沒有price member當然不能a.price
07/22 21:15, 1F

07/22 21:20, , 2F
故a.name為Some Actions也不足為奇
07/22 21:20, 2F

07/22 21:21, , 3F
interface裡的變數會自動變成static變數
07/22 21:21, 3F
文章代碼(AID): #1JpWdA-j (java)
文章代碼(AID): #1JpWdA-j (java)