判断一个对象是什么类型
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); // 编译失败
}
}
原文:https://www.cnblogs.com/juanbao/p/15018731.html