训练 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 {
}