关于instanceof

转一个网上的提问:
Integer   n   =   new   Integer(3);
boolean   bo3   =   n   instanceof   String;
System.out.println(bo3);
这样,我认为应该打印出false
但是编译的时候报错了:
Incompatible   conditional   operand   types   Integer   and   String
说Integer   和   String有矛盾!
但是我认为打印出来应该是false才对!

不知道boolean   bo3   =   n   instanceof   String;这句话为什么编译会提示那样的错误?
谢谢!

 

答案:

晕,A转为B有三种情况
1.不可能
Integer   --> String  
2.一定可以  
String   ---> Object
3.有可能(运行是才知道)
Object   ----> String

上面的类型都是编译时类型!

前两者都是编译时就知道,所有我们不会用它
但是编译器好像只阻止了第一种情况,而没有阻止第二种情况,就相当域我们写if(1==1)   也不会出错.
如果在return   语句后还有代码,一般编译不错,但是如果改为
if(ture)   return;   就可以编译通过了.

书上复习题:

 

package Review09;

public class Review_9_8 {
 public static void main(String[] args){
  GoldenDelicious fruit=new GoldenDelicious();
  Orange orange=new Orange();
//  System.out.println((fruit instanceof Orange));//A转为B有三种情况
  System.out.println((fruit instanceof Apple));
  System.out.println((fruit instanceof GoldenDelicious));
//  System.out.println((fruit instanceof Macintosh));//一定不可能
  System.out.println((orange instanceof Orange));//一定能
  System.out.println((orange instanceof Fruit));
//  System.out.println((orange instanceof Apple));
  fruit.makeApple();
//  orange.makeApple();
  orange.makeOrangeJuice();
//  fruit.makeOrangeJuice();

 

 

 

//测试,这个就可以了,是false
  Fruit fruit1=new Fruit();
  System.out.println((fruit1 instanceof Apple));//有可能
  
 }
}
class Fruit{
 public Fruit(){
  
 }
}
class Orange extends Fruit{
 public void makeOrangeJuice(){
  System.out.println("make orange juice");
 }
}
class Apple extends Fruit{
 public void makeApple(){
  System.out.println("Make a Apple");
 }
}
class GoldenDelicious extends Apple{
 
}
class Macintosh extends Apple{
 
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值