instanceof和类型转换

2023-03-10,,

什么是instanceof

判断一个对象是什么类型

注意点

    X 和 Y 必须要有父子关系 否则编译都会失败
    X对象只要是Y的子类(无论 是 儿子 还是 孙子 还是 曾孙。。。。)X instanceof Y = true

示例

package com.oop;

import com.oop.demo08.Student;
import com.oop.demo08.Person;
import com.oop.demo08.Teacher; public class Applcation {
public static void main(String[] args) {
// instanceof练习
/*
* 多态 父类的引用 指向子类的实例
* student是Object的子类(相当于孙子)
* Person是Object的子类
* Student是person的子类
* */ // Object > String
// Object > Person > Student
// Object > Person > Teacher
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 p = new Student();
System.out.println(p instanceof Student); // true
System.out.println(p instanceof Person); // true
System.out.println(p instanceof Object); // true
System.out.println(p instanceof Teacher); // false
//System.out.println(p 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(p instanceof String); // 编译失败
}
}

instanceof和类型转换的相关教程结束。

《instanceof和类型转换.doc》

下载本文的Word格式文档,以方便收藏与打印。