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();
    }
}
相关推荐
martian6657 分钟前
麒麟系统下Tomcat部署Java Web程序(WAR包)及全链路问题排查指南
开发语言·tomcat·系统安全
ai.Neo7 分钟前
牛客网NC22012:判断闰年问题详解
开发语言·c++·算法
曼岛_13 分钟前
[Java实战]Spring Boot + Netty 实现 TCP 长连接客户端及 RESTful 请求转发(二十六)
java·spring boot·tcp/ip
好吃的肘子14 分钟前
ElasticSearch进阶
大数据·开发语言·分布式·算法·elasticsearch·kafka·jenkins
老友@18 分钟前
Spring Data Elasticsearch 中 ElasticsearchOperations 构建查询条件的详解
java·后端·spring·elasticsearch·operations
NaclarbCSDN20 分钟前
Java集合框架
java·开发语言·前端
xiaohanbao0924 分钟前
day26 Python 自定义函数
开发语言·python·学习·机器学习·信息可视化·numpy
jie1889457586627 分钟前
c++,windows,多线程编程详细介绍
开发语言·c++
破晓的历程27 分钟前
Qt file文件操作详解
开发语言·qt
蟹至之30 分钟前
万字解析:Java字符串
java·字符串·stringbuilder·string·stringbuffer