欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

instanceof和类型转换

程序员文章站 2022-06-04 08:45:48
...

instanceof和类型转换

测试类

import com.study_java.oop.Demo07.Student;
import com.study_java.oop.Demo07.Person;
import com.study_java.oop.Demo07.Teacher;

public class Application {
    public static void main(String[] args) {

        //Object->Person->Student
        //Object->Person->Teacher
        //Object->String
        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 Object);//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(person instanceof String);//编译报错
    }

}

Person类

package com.study_java.oop.Demo07;

public class Person {
 
}

Student类

package com.study_java.oop.Demo07;

public class Student extends Person{

}

Teacher类

package com.study_java.oop.Demo07;

public class Teacher extends Person{
}

上一篇: MySQL数据库表的操作

下一篇: MISC