java学习笔记011 关于instanceof关键字

1.父类、子类
说明:以下类具有继承关系
|--Employee
	|--Programmer
		|--Designer
			|--Architect
//对象 instanceof 本类或其父类  结果为true
Employee emp = new Programmer();
System.out.println(emp instanceof Employee);	//true
System.out.println(emp instanceof Programmer);	//true
System.out.println(emp instanceof Designer);	//false
System.out.println(emp instanceof Architect);	//false
2.两种写法的逻辑问题
//写法一
if(p instanceof Architect){
	if(numOfArch >= 1){
		throw new TeamException("团队中至多有1名架构师");
	}
}else if(p instanceof Designer){
	if(numOfDes >= 2){
		throw new TeamException("团队中至多有2名设计师");
	}
}else if(p instanceof Programmer){
	if(numOfPro >= 3){
		throw new TeamException("团队中至多有3名程序员");
	}
}
team.add(p);

//写法二
if(p instanceof Architect && numOfArch >= 1){
	throw new TeamException("团队中至多有1名架构师");
}else if(p instanceof Designer && numOfDes >= 2){
	throw new TeamException("团队中至多有2名设计师");
}else if(p instanceof Programmer && numOfPro >= 3){
	throw new TeamException("团队中至多有3名程序员");
}
team.add(p);

第二种写法有缺陷
	如果出现p是设计师,设计师满了,程序员不满的情况,p也会被加入到团队中
	如果出现p是架构师,架构师未满,设计师已满,会抛出"团队中至多有2名设计师"这样的异常信息,所以这种
注意使用instanceof可能会出现这种情况
posted @ 2022-08-18 17:26  香菇无盐  阅读(23)  评论(0)    收藏  举报