引用类型的检查
本章重点内容。
有时候需要在运行时判断一个对象是否属于某个引用类型,这是可以引用instanceof运算符。instanceof运算符语法格式如下:
> obj instanceof type
obj是一个对象,type是引用类型,如果obj对象是type引用类型实例,则返回true,否则返回false。
话不多说,直接上代码:
package com.three; //引用类型的检查 public class Person { protected String name; protected int age; public Person(String name,int age){ this.name = name; this.age = age; } @Override public String toString(){ return "Person [name="+name+", age="+age+"]"; } } //继承Person类 class Woker extends Person{ private String factory; public Woker(String name, int age,String factory) { super(name, age); this.factory = factory; } @Override public String toString(){ return "Worker [factory="+factory+",name="+name+",age="+age+"]"; } } //继承Person类 class Student extends Person{ String school; public Student(String name, int age,String school) { super(name, age); this.school =school; } @Override public String toString(){ return "Student [school="+school+", name="+name+", age="+age+"]"; } } //调用代码 class Ssds{ public static void main(String[] args) { Student student1 = new Student("张三",18,"清华大学"); Student student2 = new Student("李四",20,"清华大学"); Student student3 = new Student("王五",21,"清华大学"); Woker woker1 = new Woker("张大娘",39,"电厂"); Woker woker2 = new Woker("李大爷",34,"水厂"); //定义一个数组来存储对象 Person[] people = {student1,student2,student3,woker1,woker2}; int studentcount = 0; int workcount = 0; //for的增强语句,item为对象, for(Person item:people){ // 引用类型的检查 if(item instanceof Student){ studentcount++; } else if(item instanceof Woker){ workcount++; } } System.out.printf("工人人数:%d,学生人数:%d",workcount,studentcount); } }
输出结果如下:
工人人数:2,学生人数:3