JAVA面向对象-----instanceof 关键字

instanceof 关键字
1:快速演示instanceof

    Person p=new Person();
        System.out.println( p instanceof Person);

2:instanceof是什么?

1:属于比较运算符:
2:instanceof关键字:该关键字用来判断一个对象是否是指定类的对象。
3:用法:
对象 instanceof 类;
该表达式是一个比较运算符,返回的结果是boolea类型 true|false
注意:使用instanceof关键字做判断时,两个类之间必须有关系。

3:案例
定义一个功能表函数,根据传递进来的对象的做不同的事情,如果是狗让其看家,如果是猫让其抓老鼠

1:定义动物类
2:定义狗类继承动物类
3:定义猫类继承动物类
4:定义功能根据传入的动物,执行具体的功能
5:instanceof好处可以判断对象是否是某一个类的实例

/*
 instanceof
 比较运算符
 检查是否是类的对象
    1:可以判断对象是否是某一个类的实例
    用法
    对象  instanceof 类; 

 案例
定义一个功能函数,根据传递进来的对象的做不同的事情
    如果是狗让其看家,如果是猫让其抓老鼠
1:定义动物类
2:定义狗类继承动物类
3:定义猫类继承动物类
4:定义功能根据传入的动物,执行具体的功能
 */

class Animal {

    String name;

    void eat() {
        System.out.println("吃东西");
    }

    void shout() {
        System.out.println("我是动物");
    }
}

class Dog extends Animal {

    void eat() {
        System.out.println("啃骨头");
    }

    void shout() {
        System.out.println("旺旺");
    }

}

class Cat extends Animal {

    void eat() {
        System.out.println("吃老鼠");
    }

    void shout() {
        System.out.println("喵喵");
    }
}

class Demo11 {

    public static void main(String[] args) {

        Demo11 d = new Demo11();

        // 对象 instanceof 类;
        System.out.println(d instanceof Demo11);

         d.doSomething(new Dog());
        d.doSomething(new Cat());
    }

    // 定义一个功能函数,根据传递进来的对象的做不同的事情
    // 如果是狗让其看家,如果是猫让其抓老鼠
    // 对象 instanceof 类;
    void doSomething(Animal a) {
        if (a instanceof Dog) {
            a.eat();
            a.shout();
            System.out.println("小狗看家");
        } else if (a instanceof Cat) {
            a.eat();
            a.shout();
            System.out.println("抓老鼠");
        }
    }
}

练习:

        byte[] bs = new byte[] { 1, 2, 3 };
        int[] is = new int[] { 1, 2, 3 };
        String[] ss = new String[] { "jack", "lucy", "lili" };
        System.out.println(bs instanceof byte[]); // true
        System.out.println(is instanceof int[]); // true
        System.out.println(ss instanceof String[]); // true
        // System.out.println(bs instanceof int[]); // 不可转换的类型

【正在看本人博客的这位童鞋,我看你气度不凡,谈吐间隐隐有王者之气,日后必有一番作为!下面有个“顶”字,你就顺手把它点了吧(要先登录CSDN账号哦 )】


—–乐于分享,共同进步!
—–更多文章请看:http://blog.csdn.net/duruiqi_fx


原文地址:https://www.cnblogs.com/hainange/p/6153860.html