Comparing Class Types in Java

前端 未结 8 2035
不知归路
不知归路 2020-12-14 06:07

I want to compare the class type in Java.

I thought I could do this:

class MyObject_1 {}
class MyObject_2 extends MyObject_1 {}

public boolean funct         


        
8条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-14 06:23

    Try this:

    MyObject obj = new MyObject();
    if(obj instanceof MyObject){System.out.println("true");} //true
    

    Because of inheritance this is valid for interfaces, too:

    class Animal {}
    class Dog extends Animal {}    
    
    Dog obj = new Dog();
    Animal animal = new Dog();
    if(obj instanceof Animal){System.out.println("true");} //true
    if(animal instanceof Animal){System.out.println("true");} //true
    if(animal instanceof Dog){System.out.println("true");} //true
    

    For further reading on instanceof: http://mindprod.com/jgloss/instanceof.html

提交回复
热议问题