Java(基础)多态参数方法、造型instanceof关键字

package com.day12.Polymorphism;

public class PersonTest3 {

    //方法可以接收任意Person及子类对象,兼容性提高了
    public static void test(Person p) {//接收对象,参数就是父类类型的,这样的方法称为多态参数方法
        p.sayHello();

        //p.spring();多态副作用

        //instanceof 判断左侧引用指向对象的实体是否是 右侧的类型的一个对象,如果是,返回true,不是返回false
        if (p instanceof Beijing) {
            System.out.println("北京人");
        } else if (p instanceof Chinese) {
            Chinese ch = (Chinese) p;//造型 造型有风险!!必须先判断
            ch.spring();
        } else if (p instanceof American) {
            ((American) p).christmas();
        } else {
            System.out.println("普通人");//顺序很重要,大范围在下,小范围在上
        }

    }

    public static void main(String[] args) {
        Chinese ch = new Chinese("张三", 30, "男", "虎");
        American am = new American("Banner", 20, "male", true);
        Person p = new Person("someBody", 25, "unknown");
        Beijing bj = new Beijing("李四", 40, "女", "猪");

        test(bj);
    }

}
public class ComputerTest2 {
    public static void listPrice(Computer com){
        System.out.println(com.getPrice());
        if(com instanceof PC ){
            PC pc = (PC) com;
            pc.code();
        }else if (com instanceof NotePad){
            ((NotePad)com).navigate();
        }else{
            System.out.println("普通电脑");
        }
    }

    public static void main(String[] args) {
        listPrice(new NotePad(2.6, 16, 400, 8999, 8));
        listPrice(new PC(3.5, 8, 500, 3999, "cherry"));
        listPrice(new Computer(3, 4, 300, 2000));


    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值