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();
    }
}
相关推荐
ahardstone1 分钟前
【CS61A 2024秋】Python入门课,全过程记录P5(Week8 Inheritance开始,更新于2025/2/2)
开发语言·python
阿豪学编程17 分钟前
c++ string类 +底层模拟实现
开发语言·c++
test猿17 分钟前
hive为什么建表,表存储什么
java
程序猿零零漆1 小时前
SpringCloud系列教程:微服务的未来(二十)Seata快速入门、部署TC服务、微服务集成Seata
java·spring·spring cloud·微服务
沈韶珺1 小时前
Visual Basic语言的云计算
开发语言·后端·golang
沈韶珺1 小时前
Perl语言的函数实现
开发语言·后端·golang
嘻嘻哈哈的zl2 小时前
初级数据结构:栈和队列
c语言·开发语言·数据结构
wjs20242 小时前
MySQL 插入数据指南
开发语言
美味小鱼2 小时前
Rust 所有权特性详解
开发语言·后端·rust
我的K84092 小时前
Spring Boot基本项目结构
java·spring boot·后端