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();
    }
}
相关推荐
‿hhh几秒前
综合交通运行协调与应急指挥平台项目说明
java·ajax·npm·json·需求分析·个人开发·规格说明书
小徐Chao努力几秒前
【Langchain4j-Java AI开发】06-工具与函数调用
java·人工智能·python
无心水3 分钟前
【神经风格迁移:全链路压测】33、全链路监控与性能优化最佳实践:Java+Python+AI系统稳定性保障的终极武器
java·python·性能优化
萧曵 丶12 分钟前
Synchronized 详解及 JDK 版本优化
java·多线程·synchronized
夏幻灵27 分钟前
JAVA基础:基本数据类型和引用数据类型
java·开发语言
weixin1997010801633 分钟前
闲鱼 item_get - 商品详情接口对接全攻略:从入门到精通
java·后端·spring
cike_y1 小时前
Spring-Bean的作用域&Bean的自动装配
java·开发语言·数据库·spring
qq_12498707531 小时前
基于深度学习的蘑菇种类识别系统的设计与实现(源码+论文+部署+安装)
java·大数据·人工智能·深度学习·cnn·cnn算法
十八度的天空1 小时前
第01节 Python的基础语法
开发语言·python
谈笑也风生1 小时前
经典算法题型之排序算法(三)
java·算法·排序算法