关于instanceof

    技术2024-12-20  44

    转一个网上的提问: 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)