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();
    }
}
相关推荐
0xDevNull3 小时前
Java反射机制深度解析:从原理到实战
java·开发语言·后端
小小亮013 小时前
Next.js基础
开发语言·前端·javascript
华科易迅3 小时前
MybatisPlus增删改查操作
android·java·数据库
ALex_zry3 小时前
C++网络编程心跳机制与连接保活:长连接稳定性保障
开发语言·网络·c++
standovon4 小时前
Spring Boot整合Redisson的两种方式
java·spring boot·后端
Amumu121384 小时前
Js:正则表达式(二)
开发语言·javascript·正则表达式
Sgf2274 小时前
ES8(ES2017)新特性完整指南
开发语言·javascript·ecmascript
IAUTOMOBILE4 小时前
Python 流程控制与函数定义:从调试现场到工程实践
java·前端·python
hutengyi4 小时前
PostgreSQL版本选择
java
皮皮林5514 小时前
重磅!JetBrains 正式发布全新的 AI 开发工具,定名 AI IDE AIR
java·intellij idea