第五章 继承、多态、抽象类与接口 课后训练(7)

        训练 13 教师与学生

        使用多态编写一个程序,在控制台上输出如下内容。其中人类既是教师类的父类,也是学生的父类。

public class people {
    public  void work(people a){
        //如果传入对象是教师类
        if(a instanceof teacher){
            System.out.println("老师要认真授课");
        } else if (a instanceof student) {//如果传入对象是学生类
            System.out.println("学生要好好学习");
        }else if (a instanceof people) {//如果传入对象是人类
            System.out.println("每个人都要工作");
        }
    }
    public static void main(String[] args) {
        //创建一个人类对象
        people p = new people();
        p.work(p);
        //创建一个教师类对象
        teacher t = new teacher();
        t.work(t);
        //创建一个学生类对象
        student s = new student();
        s.work(s);
    }
}
class teacher extends people{

}
class student extends people {}

        训练 14 交通灯亮几秒

        使用instanceof关键字模拟交通红绿灯的点亮时间。

public class light {
    public void statue(light a){
        //判断输入的不同的对象进行不同的输出
        if (a instanceof red){
            System.out.println("红灯亮45秒");
        }else if (a instanceof green){
            System.out.println("绿灯亮30秒");
        }else if (a instanceof yellow){
            System.out.println("黄灯亮5秒");
        }
    }
    public static void main(String[] args) {
        //创建三个类对相应的三个对象
        red red = new red();
        green green = new green();
        yellow yellow = new yellow();
        //分别调用statue方法
        red.statue(red);
        yellow.statue(yellow);
        green.statue(green);


    }
}
//创建红灯类
class red extends light {

}
//创建绿灯类
class green extends light {

}
//创建黄灯类
class yellow extends light {

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值