Java三大特征--多态

1、程序运行的最终结果只在执行期间才被确定,编译时无法确定
2、编译时所用参数类型一般为父类,运行时参数类型为确定的子类
3、三个必要条件:要有继承,子类要有方法的重写,父类引用指向子类对象(只可向上转型,不可向下转型)

测试例子如下:

package cn.ldedu;


/**
 * 测试多态
 * @author Lenovo
 *
 */
class Animal{
    public void sing(){
        System.out.println("aaa");
    }
}


class Cat extends Animal{
    public void sing(){
        System.out.println("喵喵喵");
    }

    public void catchMouse(){
        System.out.println("抓老鼠");
    }
}


class Dog extends Animal{
    public void sing(){
        System.out.println("汪汪汪");
    }
}

/**
 * 测试类
 * @author Lenovo
 *
 */
public class testduotai {
    public void testsing(Animal a){
        a.sing();


        // 测试instanceof方法
        if(a instanceof Cat)
            ((Cat)a).catchMouse();//调用方法前一定要强制转型

    }

    public static void main(String[] args) {

        testduotai tt=new testduotai();

        //Animal 向下转型为Cat
        Animal a=new Cat(); 
        Dog b=new Dog();//避免了转型,但是不推荐使用

        tt.testsing(a);
        tt.testsing(b);

        //此时若"a"想调用catchMouse方法,需要强制转型,或者也可以在测试方法中利用instanceof方法调用catchMouse方法
        Cat cc=(Cat)a;
        cc.catchMouse();


    }
}

运行截图:这里写图片描述

关于抽象类、接口、回调会在其他文章详细描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值