首页 > 其他 > 详细

instanceof和类型转换

时间:2021-07-16 10:48:30      阅读:12      评论:0      收藏:0      [点我收藏+]

什么是instanceof

判断一个对象是什么类型

注意点

  1. X 和 Y 必须要有父子关系 否则编译都会失败
  2. 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和类型转换

原文:https://www.cnblogs.com/juanbao/p/15018731.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!