代码举例
// 嵌套循环 if (p instanceof Architect) { if (numOfArc >= 1) { throw new TeamException("每个团队中最多只能有一名架构师"); } } else if (p instanceof Designer) { if (numOfDes >= 2) { throw new TeamException("团队中至多只能有两名设计师"); } } else if (p instanceof Programmer) { if (numOfPro >= 3) { throw new TeamException("团队中至多只能有三名程序员"); } } // && if (p instanceof Architect && numOfArc >= 1) { throw new TeamException("每个团队中最多只能有一名架构师"); } else if (p instanceof Designer && numOfDes >= 2) { throw new TeamException("团队中至多只能有两名设计师"); } else if (p instanceof Programmer && numOfPro >= 3) { throw new TeamException("团队中至多只能有三名程序员"); }
其中,Architect继承于Designer,Designer继承于Programmer;
1、嵌套循环中,如果p instanceof Architect为true,numOfArc >= 1 为false,结果不会抛出异常throw new TeamException("每个团队中最多只能有一名架构师"),下面的else if都不会被执行。
2、&&中,如果p instanceof Architect为true,numOfArc >= 1 为false,则没有进入第一个if语句,结果也不会抛出异常throw new TeamException("每个团队中最多只能有一名架构师"),但是会开始向下执行else if语句,如果满足 p instanceof Designer && numOfDes >= 2 或者 p instanceof Programmer && numOfPro >= 3 的条件则可能会执行相应的else if语句,造成逻辑错误。
3、综上,&& 的实现方法在极端情况下(存在继承关系),会导致本该在A下进行的判断,错误地执行到A的父类B中进行判断,导致逻辑错误。
4、追本溯源,在写程序是要捋清逻辑:先判断传入的对象p是否属于Architect、Designer或Programmer类,然后在各自的条件下进行判断,是先后关系;如果采用&&,那就是需要满足两个条件,就变成并列关系了。
注:本文中的代码来源于B站尚硅谷宋红康老师的30天搞定Java基础课程
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)