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();
    }
}
相关推荐
CodeCraft Studio7 分钟前
国产化PDF处理控件Spire.PDF教程:如何在 Java 中通过模板生成 PDF
java·python·pdf·spire.pdf·java创建pdf·从html创建pdf
echoarts17 分钟前
MATLAB R2025a安装配置及使用教程(超详细保姆级教程)
开发语言·其他·matlab
阿方.91828 分钟前
《数据结构全解析:栈(数组实现)》
java·开发语言·数据结构
YC运维33 分钟前
Ansible题目全解析与答案
java·算法·ansible
程序员清风42 分钟前
贝壳一面:年轻代回收频率太高,如何定位?
java·后端·面试
考虑考虑1 小时前
Java实现字节转bcd编码
java·后端·java ee
Dovis(誓平步青云)1 小时前
《探索C++11:现代语法的内存管理优化“性能指针”(下篇)》
开发语言·jvm·c++
charlie1145141911 小时前
前端三件套简单学习:HTML篇1
开发语言·前端·学习·html
kebeiovo1 小时前
项目必备流程图,类图,E-R图实例速通
开发语言·r语言·流程图
软件开发-NETKF88881 小时前
JSP到Tomcat特详细教程
java·开发语言·tomcat·jsp·项目运行