public void method(Employee e){
if (e instanceof Manager){
}
else if (e instanceof Contractor){
}
else{
}
}
instanceof关键字: 判断指定对象是否某类型的对象 比如,在程序中,如果Employee是从Manager间接或直接继承的 那么 "e instanceof Manager "返回true 否则返回 false
实际运用中主要注意下面几点:
1. 子类实例 instanceof 父类 返回 true
2. 父类实例 instanceof 子类 返回 false
3. 如果两个类不在同一继承家族中,使用instanceof时会出现inconvertible types错误,编译都通不过。
注意:以下使用也是正确的,运行test3的结果 是 在控制台打印出"I do it":
public class test3 {
public static void main(String[] args){
Level level = new Level();
Object object = level;
if(object instanceof Level){
System.out.println("I do it");
}
}
}
public class Level {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}