「Java」「extends & method」 Chapter3 Question4

Given:
public class Test4 {
 public static void main(String[] args) {
  Employee e1 = new Employee();
  System.out.println(e1.getDepartment());// stuff

  Employee e2 = new Manager();
  System.out.println(e2.getDepartment());// stuff

  Employee e3 = new GeneralManager();
  System.out.println(e3.getDepartment());// GeneralManager

  Employee e4 = new CEO();
  System.out.println(e4.getDepartment());// CEO

  // Manager m1 = new Employee();//編譯錯誤: 子=父
  // System.out.println(m1.getDepartment());

  Manager m2 = new Manager();
  System.out.println(m2.getDepartment());// stuff

  Manager m3 = new GeneralManager();
  System.out.println(m3.getDepartment());// GeneralManager

  Manager m4 = new CEO();
  System.out.println(m4.getDepartment());// CEO

  // GeneralManager g1 = new Employee();//編譯錯誤: 子=父
  // System.out.println(m1.getDepartment());

  //GeneralManager g2 = new Manager();////編譯錯誤: 子=父
  //System.out.println(m2.getDepartment());

  GeneralManager g3 = new GeneralManager();
  System.out.println(g3.getDepartment());// GeneralManager

  GeneralManager g4 = new CEO();
  System.out.println(g4.getDepartment());// CEO
 }
}

class Employee {
 String department = "Stuff";

 public String getDepartment() {
  return department;
 }
}

class Manager extends Employee {
 //manager沒有getDepartment方法,也就無法取得欄位資訊
 String department = "Manager";
}

class GeneralManager extends Manager {
 String department = "GeneralManager";
 public String getDepartment() {
  return department;
 }
}

class CEO extends GeneralManager {
 public String getDepartment() {
  return "CEO";
 }
}


Anaswer:
Stuff
Stuff
GeneralManager
CEO
Stuff
GeneralManager
CEO
GeneralManager
CEO

---------------------------------------------------------------------
Manager 只有物件欄位,沒有物件方法 getDepartment,導致在呼叫Manager的department資訊時,會從父類別 Employee 中取得 department 資訊。

留言

這個網誌中的熱門文章

[Excel]國曆轉農曆VBA

「CSS」「div區塊介紹」 三欄式網頁排版設計

「生活」眉毛觀人