java之多型(Polymorphic)、動態繫結(Dynamic Binding)、遲繫結(Late Binding)

高傑才_Android發表於2014-10-19

今天,我們來說說java物件導向最核心的東西,多型。通過多型可以使我們的程式可複用性達到極致,這就是我們為什麼要學多型的原因。

“多型”(Polymorphic)也叫“動態繫結”(Dynamic Binding)同時也叫“遲繫結”(Late Binding)。

動態繫結是指“在執行期間(而非編譯期間)判斷所引用物件的實際型別,根據其實際型別呼叫其相應的方法。”

程式程式碼:

public class TestPolymorphic{
    public static void main(String args[]){
    
        Animal animal = new Animal("animal");
        Cat cat = new Cat("cat","blue");
        Dog dog = new Dog("dog","black");
        
        Lily l1 = new Lily("l1",animal);
        Lily l2 = new Lily("l1",dog);
        
        l1.myAnimalEnjoy();
        l2.myAnimalEnjoy();
    }
}
class Lily{
    private String name;
    private Animal animal;
    public Lily(String name, Animal animal){
        this.name = name;
        this.animal = animal;
    }
    public void myAnimalEnjoy(){
        animal.enjoy();
    }
}
class Animal{
    private String name;
    public Animal(String name){
        this.name = name;
    }
    public void enjoy(){
        System.out.println("叫聲~~~");
    }
}
class Dog extends Animal{
    
    private String forlorColor;
    public Dog(String name,String forlorColor){
        super(name);
        this.forlorColor = forlorColor;
    }
    public void enjoy(){
        System.out.println("dog叫聲~~~");
    }
}
class Cat extends Animal{
    
    private String eyesColor;
    public Cat(String name,String eyesColor){
        super(name);
        this.eyesColor = eyesColor;
    }
    public void enjoy(){
        System.out.println("cat叫聲~~~");
    }
}

程式執行結果:

總結:通過以上示例,我們發現多型必備的三個條件1、有繼承2、有重寫3、父類引用指向子類物件

相關文章