码迷,mamicode.com
首页 > 编程语言 > 详细

java之多态(Polymorphic)、动态绑定(Dynamic Binding)、迟绑定(Late Binding)

时间:2014-10-19 18:22:58      阅读:208      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   ar   java   for   sp   div   

今天,我们来说说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叫声~~~");
    }
}

程序运行结果:

bubuko.com,布布扣

总结:通过以上示例,我们发现多态必备的三个条件1、有继承2、有重写3、父类引用指向子类对象

java之多态(Polymorphic)、动态绑定(Dynamic Binding)、迟绑定(Late Binding)

标签:style   blog   http   color   ar   java   for   sp   div   

原文地址:http://www.cnblogs.com/Gaojiecai/p/4035077.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!