codecamp

多态

多态 定义:

多态是同一个行为具有多个不同表现形式或形态的能力。

理解方法: 以Animal、Dog、Cat类为例,它们都有eat方法,如果使用以下代码:

Animal animal = new Dog();
animal.eat();
animal = new Cat();
animal.eat();
java执行流程:
java会先看Animal中是否有eat方法的定义:{
    如果没有则会报错;
    如果有则java会再看实例化对象的类中是否有eat方法的实现{
        如果没有则java会看Animal中是否有eat方法的实现{
            如果没有则会报错;
            如果有则会调用;
        }
        如果有则会调用实例化对象的类中的eat方法。
    }
}

以下为Animal为类、抽象类、接口时的代码示例: 1.Animal为类时代码示例:

class Animal{
    public void eat() {
        System.out.println("Animal吃东西。");
    }
}
class Dog extends Animal{
    public void eat() {
        System.out.println("Dog吃东西。");
    }
}
class Cat extends Animal{
    public void eat() {
        System.out.println("Cat吃东西。");
    }
}

2.Animal为抽象类时代码示例:

abstract class Animal{
    public abstract void eat();
}
class Dog extends Animal{
    public void eat() {
        System.out.println("Dog吃东西。");
    }
}
class Cat extends Animal{
    public void eat() {
        System.out.println("Cat吃东西。");
    }
}

3.Animal为接口时代码示例:

interface Animal{
    public void eat();
}
class Dog implements Animal{
    public void eat() {
        System.out.println("Dog吃东西。");
    }
}
class Cat implements Animal{
    public void eat() {
        System.out.println("Cat吃东西。");
    }
}
I/O
访问修饰符
温馨提示
下载编程狮App,免费阅读超1000+编程语言教程
取消
确定
目录

关闭

MIP.setData({ 'pageTheme' : getCookie('pageTheme') || {'day':true, 'night':false}, 'pageFontSize' : getCookie('pageFontSize') || 20 }); MIP.watch('pageTheme', function(newValue){ setCookie('pageTheme', JSON.stringify(newValue)) }); MIP.watch('pageFontSize', function(newValue){ setCookie('pageFontSize', newValue) }); function setCookie(name, value){ var days = 1; var exp = new Date(); exp.setTime(exp.getTime() + days*24*60*60*1000); document.cookie = name + '=' + value + ';expires=' + exp.toUTCString(); } function getCookie(name){ var reg = new RegExp('(^| )' + name + '=([^;]*)(;|$)'); return document.cookie.match(reg) ? JSON.parse(document.cookie.match(reg)[2]) : null; }