java instanceof运算符。

Java instanceof运算符


instanceof运算符用于测试指定对象是否是指定类型(类或子类或接口)的实例,它返回true或false。 如果对任何具有null值的变量应用instanceof运算符,则返回false。

class Simple {
    public static void main(String args[]) {
        Simple s = new Simple()
        System.out.println(s instanceof Simple);// true
    }
}

输出结果

true

因为s是Simple类的实例对象,所以为true。
如果用null值测试

class Dog2 {
    public static void main(String args[]) {
        Dog2 d = null;
        System.out.println(d instanceof Dog2);// false
    }
}

返回

false

转型:
向下转型:

 Animal a = new Dog(); 

向上转型:

 Dog d = new Animal();                                            //向上转型会报错,抛出ClassCastException异常

同时也不能强转

 Dog d = (Dog)new Animal();                                   //抛出异常,并不能强转原生的Animal类对象

但是可以强转向下转型后的对象,例如:

Animal a = new Dog();                                                //提升为Animal,但是引用的是dog对象。
Dog d = (Dog) a;                                                         //引用的是Dog对象就可以强转成Dog对象。

但是

Animal a = new Dog();                                      //提升为Animal,但是引用的是dog对象。            
a = new Animal();                                             //之后又引用到Animal对象 。 
Dog d = (Dog) a;                                               //当然Animal对象是不能强转成Dog对象的。

总之能否强转,看被强转类型是否和将要强转的类型相同就可以了。如果实在不知道能否强转就使用instanceof判断一下,若instanceof返回true,就可以强转,反之不行。

class Animal {
}

class Dog3 extends Animal {
    static void method(Animal a) {
        if (a instanceof Dog3) {
            Dog3 d = (Dog3) a;// downcasting
            System.out.println("ok downcasting performed");
        }
    }

    public static void main(String[] args) {
        Animal a = new Dog3();
        Dog3.method(a);
    }
}

输出结果

ok downcasting performed

示例

interface Printable {
}

class A implements Printable {
    public void a() {
        System.out.println("a method");
    }
}

class B implements Printable {
    public void b() {
        System.out.println("b method");
    }
}

class Call {
    void invoke(Printable p) {// upcasting
        if (p instanceof A) {
            A a = (A) p;// Downcasting
            a.a();
        }
        if (p instanceof B) {
            B b = (B) p;// Downcasting
            b.b();
        }

    }
}// end of Call class

class Test4 {
    public static void main(String args[]) {
        Printable p = new B();
        Call c = new Call();
        c.invoke(p);
    }
}

输出结果

b method

猜你喜欢

转载自blog.csdn.net/weixin_43101144/article/details/84874876
今日推荐