JavaSE-判断对象类型

instancof

instanceof不仅可以判断对象是不是某个类的实例,还可以判断对象继承的基类和实现的接口。

public interface Study {
    public void study();
}

public class Student implements Study{
    @Override
    public void study() {

    }
}

public class ArtStudent extends Student{

}

public class InstanceofTest {
    public static void main(String[] args) {
        ArtStudent artStudent = new ArtStudent();
        if (artStudent instanceof ArtStudent)
            System.out.println("It is ArtStudent");
        if (artStudent instanceof Student)
            System.out.println("It is Student");
        if (artStudent instanceof Study)
            System.out.println("It implements Study");
    }
}

//    It is ArtStudent
//    It is Student
//    It implements Study

Class.equals()

Class.equals()可以精确判断对象是否是某个类的实例,无法判断其继承的基类和实现的接口。

public class ClassEqualsTest {
    public static void main(String[] args) {
        ArtStudent artStudent = new ArtStudent();
        if (artStudent.getClass().equals(ArtStudent.class))
            System.out.println("It is ArtStudent");
        if (artStudent.getClass().equals(Student.class))
            System.out.println("It is Student");
        if (artStudent.getClass().equals(Study.class))
            System.out.println("It implements Study");
    }
}

//It is ArtStudent
posted @ 2022-04-30 00:07  clearHeart99  阅读(183)  评论(0编辑  收藏  举报