Java之instanceof

来源:互联网 发布:用js设置秒表 编辑:程序博客网 时间:2024/06/17 12:45

instanceof 运算符         判断该对象是否是某一个类的实例

语法格式                 boolean  b = 对象 A  instanceof 类B ;//判断A对象是否是B类的实例,如果是,返回true

instanceof 运算符

若对象是类的实例返回true

若对象是类的父类的实例也返回true

//父类class Person{String name;int age;public void work(){System.out.println("不知道工作干什么");}}//子类Studentclass Student extends Person{public void work(){System.out.println("我的工作就是上课认真听讲老师");}}class Teacher extends Person{public void work(){System.out.println("我的工作就是认真给同学讲课");}}class Combine{public void work(Person p){if(p instanceof Student){Student stu = new Student();stu.work();}else{Teacher tea = new Teacher();tea.work();}}}public class Demo {public static void main(String[] args) {//创建学生对象Person p = new Student();Combine com = new Combine();com.work(p);p = new Teacher();com.work(p);}}