構成多型的條件有三項,如下:

1.  要有繼承 (extends)

2. 一定有重寫 (override) 父類方法

3. 父類引用指向子類物件

當三個條件滿足,當你調父類中被重寫的方法時,實際是在調用new出來的子類物件方法,換言之,當你重寫父類方法時,你new出一個子類物件後,調用的就是子類物件中重寫的方法

可參考以下程式碼:

class Animal {
    public String name;
    Animal(String name){
        this.name = name;
    }
    
    public void enjoy() {
        System.out.println("叫聲...");
    }    
}

class Cat extends Animal {
    public String eyesColor;
    Cat(String n, String c) {
        super(n);
        this.eyesColor = c;
    }
    
    public void enjoy() {
        System.out.println("貓叫聲...");
    }    
}

class Dog extends Animal {
    public String furColor;
    Dog (String n, String f){
        super(n);
        this.furColor = f;
    }
    
    public void enjoy() {
        System.out.println("狗叫聲...");
    }    
}

class Bird extends Animal {
    public String furColor;
    Bird (String n, String f) {
        super(n);
        this.furColor = f;
    }
    
    public void enjoy() {
        System.out.println("鳥叫聲...");
    }    
}

class Lady {
    protected String name;
    private Animal pet;
    
    Lady (String name, Animal pet) {
        this.name = name;
        this.pet = pet;
    }
    
    public void myPetEnjoy() {
        pet.enjoy();
    }
}

public class TestPolymorphism {
    
    public static void main(String[] args) {
        
        Cat c = new Cat("Cat", "bule");
        Dog d = new Dog("Dog", "black");
        Bird b = new Bird("Bird", "green");a
        Lady l1 = new Lady("Cindy", c);
        Lady l2 = new Lady("阿美", d);
        Lady l3 = new Lady("小花", b);
        
        System.out.print(l1.name + "的寵物發出");
        l1.myPetEnjoy();
        System.out.print(l2.name + "的寵物發出");
        l2.myPetEnjoy();
        System.out.print(l3.name + "的寵物發出");
        l3.myPetEnjoy();
        
    }
    
}

 

arrow
arrow
    全站熱搜
    創作者介紹
    創作者 ced425 的頭像
    ced425

    Cedric's 學習備忘錄

    ced425 發表在 痞客邦 留言(0) 人氣()