2013年1月12日 星期六

多型Polymorphism

[概念]
多型作用於Instance Method上,不作用在Class Method、Class Variable和Instance Variable上

目的是為了在執行時期讓Sub Class的物件動態地選擇合適的method

pic 1: polymorphism

//Base Class
public class SuperHero{
  power(){
    System.out.println("superhuman strength");
  }
  fortune(){
    System.out.println("fortune type");
  }
}

//Sub Class
public class Spiderman extends SuperHero{
  power(){
    System.out.println("spin a web");
  }
}

public class Test{
  public static void main(String[] args){
    SuperHero sh = new Spiderman();
    sh.power();    //"spin a web"
    sh.fortune();  //"fortune type"
  }
}

變數sh宣告為SuperHero型態(稱為型式型態),但實際型態卻為Spiderman

sh.power( )會執行實際型態的method,也就是
power(){
    System.out.println("spin a web");
}


[細節]

[延伸]
抽象類別Abstract Class
介面Interface


[參考]
1. O'Reilly技術短文 OO

如有錯誤,請不吝指教

沒有留言:

張貼留言