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();
    }
}
相关推荐
王景程8 分钟前
如何测试短信接口
java·服务器·前端
安冬的码畜日常31 分钟前
【AI 加持下的 Python 编程实战 2_10】DIY 拓展:从扫雷小游戏开发再探问题分解与 AI 代码调试能力(中)
开发语言·前端·人工智能·ai·扫雷游戏·ai辅助编程·辅助编程
朝阳5811 小时前
Rust项目GPG签名配置指南
开发语言·后端·rust
朝阳5811 小时前
Rust实现高性能目录扫描工具ll的技术解析
开发语言·后端·rust
程高兴1 小时前
基于Matlab的车牌识别系统
开发语言·matlab
zhang23839061541 小时前
IDEA add gitlab account 提示
java·gitlab·intellij-idea·idea
牛马baby1 小时前
Java高频面试之并发编程-07
java·开发语言·面试
CodeWithMe1 小时前
【C++】STL之deque
开发语言·c++
卓怡学长2 小时前
w304基于HTML5的民谣网站的设计与实现
java·前端·数据库·spring boot·spring·html5
YONG823_API2 小时前
深度探究获取淘宝商品数据的途径|API接口|批量自动化采集商品数据
java·前端·自动化