java中的instanceof 的用法

1.instanceof功能:判断前面的对象是否属于后面的类,或者属于其子类; 如果是,返回 true ,不是返回 false;

2.instanceof概念是在多态中提出的

3.注意事项:

使用 instanceof 时需要保证:
instanceof 前面的引用变量编译时的类型要么与后面的类型相同,要么与后面的类型具有父子继承关系,否则就会出现编译出错。

4,代码案例:

java 复制代码
//Student类
package demo07;

public class Student extends Person{
    public void go(){
    }
}

//Person类
package demo07;

public class Person {
    public void run(){
        System.out.println("run");
    }
}

//输出
import demo07.Person;
import demo07.Teacher;
import demo07.Student;

public class Application {
    public static void main(String[] args) {
        //System.out.println(X instanceof Y );能不能编译通过!
        //object>String
        //object>Person>Teacher
        //object>Person>Student
        Object object =new Student();
        System.out.println(object instanceof Student);//true
        System.out.println(object instanceof Person);//true
        System.out.println(object instanceof Object);//true
        System.out.println(object instanceof Teacher);//False
        System.out.println(object instanceof String);//False
        System.out.println("========================");
        Person person = new Student();
        System.out.println(person instanceof Student);//true
        System.out.println(person instanceof Person);//true
        System.out.println(person instanceof Teacher);//False
        //System.out.println(person instanceof String);// 编译报错
        System.out.println("==================");
        Student student = new Student();
        System.out.println(student instanceof Student);//true
        System.out.println(student instanceof Person);//true
        System.out.println(student instanceof Object);//true
        //System.out.println(student instanceof Teacher);//编译报错
        //System.out.println(student instanceof String);//编译报错
        System.out.println("==================");
        //类型之间的转换 父     子
        Person student1 = new Student();
        //student1.go();
        //将student这个对象转换成Student这个类型,然后就可以使用Student类型的方法了
        Student student11 = (Student) student1;//快捷键,(Student,要转换的类型)student,需要转换的对象    然后Alt+回车
        student11.go();
        Student student2 = new Student();
        //子类转换为父类,可能会丢失一些自己本来的方法
        student2.go();
        Person person1 =student2;
        //person1.go();
    }
}
相关推荐
神仙别闹29 分钟前
基于Python实现英词语自动对齐系统
开发语言·python
akinggw35 分钟前
libagentcore - 一个基于c++的AI多agent系统升级到2.0版本
开发语言·jvm·c++
代码山河1 小时前
基本类型转换:自动类型转换与强制类型转换
java·学习·架构·教程·面向对象·项目
老歌老听老掉牙1 小时前
圆柱端面四平面交线及其在yoz面投影的几何解析与 Python 实现
开发语言·python·平面
旖旎夜光2 小时前
【C++ 基础入门】命名空间、输入输出、缺省参数与函数重载
开发语言·c++·笔记·学习
俩个逗号。。2 小时前
Kotlin flow 详解
android·开发语言·kotlin
Escalating_xu2 小时前
【Linux 网络编程】五种 I/O 模型与非阻塞 I/O:从“等数据”到正确处理 EAGAIN
java·linux·网络
程序猿乐锅3 小时前
万字详解Single-flight(单飞模式)
java·开发语言·分布式·后端·学习·single-flight
Java后端的Ai之路3 小时前
【AIAgent开发】-Agent工具封装成CLI(纯干货!!!)
java·javascript·人工智能·agent·cli
AntsData3 小时前
用 12K+ 条亚马逊评论信号,定位机械键盘下一版该改什么
java·大数据·计算机外设