Java編程思想——多態

多態經過分離作什麼和怎麼作,從另外一角度將接口和實現分離出來。bash

向上轉型

把某個對象的引用視爲對其及類型的引用的作法被稱做向上轉型dom

//建立樂器基類
class Instrument{
    public void play(Note n){
        print("Instrument.play()");
    }
}

public class Wind extends Instrument{

    public void play(Note n){
        print("Wind.play()"+n);
    }
}

public class Brass extends Instrument{

    public void play(Note n){
        print("Brass.play()"+n);
    }
}

public class Music{
    public static void tune(Instrument i){
        i.play()
    }

    main(String[] args){
        Wind w = new Wind();
        tune(w) //Wind.play()
    }
}複製代碼

Wind 是從Instrument繼承的,因此Instrument的接口一定存在Wind中,從Wind向上轉型到Instrument會「縮小」接口。ui

綁定

編譯器怎麼知道Instrument引用指向的是Wind對象,而不是Brass對象?spa

方法調用綁定

綁定:將一個方法調用與方法主體關聯起來稱做綁定。code

  • 前期綁定:程序執行前進行綁定
  • 後期綁定(動態綁定):運行時根據對象的類型進行綁定
    Java中除了static和final方法以外,其餘全部的方法都是後期綁定
//基類
public class Shape{
    public void draw(){

    }
    public void erase(){

    }
}

public class Circle extends Shape{
    public void draw(){
        print("Circle draw");
    }
    public void erase(){
        print("Circle erase");
    }
}

public class Square extends Shape{
    public void draw(){
        print("Square draw");
    }
    public void erase(){
        print("Square erase");
    }
}

public class Triangle extends Shape{
    public void draw(){
        print("Triangle draw");
    }
    public void erase(){
        print("Triangle erase");
    }
}

public class RandomShape{


}複製代碼
相關文章
相關標籤/搜索