多态

2018-03-21  本文已影响3人  Fight_Code

1.含义:

同一个操作作用于不同的对象上面,可以产生不同的解释和不同的执行结果,

2.例子

1).最普通的"多态"

var makeSound = function(animal){
    if(animal instance of Duck){
        console.log("duck duck...")
    }else if(animal instance of Chicken){
        console.log("chicken chicken...")
    }
};

var Duck = function(){};
var Chicken = function(){};

makeSound( new Duck() );
makeSound( new Chicken() );

2).对象的多态性

var makeSound = function( animal ){
    animal.sound();
}

var Duck = function(){}
Duck.prototype.sound = function(){
    console.log("duck duck...");
}

var Chicken = function(){}
Chicken.prototype.sound = function(){
    console.log("chicken chicken...")
}

makeSound( new Duck() );
makeSound( new Chicken() );

3.多态与继承的关系

因为js与oc这些是动态语言,不必要进行类型检查。但如果想java这些静态语言,makeSound方法的入参就必须指定变量类型。所以指定duck的时候,传入chicken会报错。这个使用就需要使用继承得到多态效果。

public abstract class Animal{
    abstract void makeSound(); //抽象方法
}

public class Chicken extends Animal{
    public void makeSound(){
        System.out.println(chicken chicken...);
    }
}

public class Duck extends Animal{
    public void makeSound(){
        System.out.println(duck duck...);
    }
}


public class AnimalSound{
    public void makeSound( Animal animal ){
        animal.makeSound();
    }
}

public class Test{
    public static void main(String args[]){
        AnimalSound animalSound = new AnimalSound();
        Animal duck = new Duck();
        Animal chicken = new Chicken();
        animalSound.makeSound(duck);
        animalSound.makeSound(chicken);
    }
}
上一篇下一篇

猜你喜欢

热点阅读