简体   繁体   中英

Java: How to if a object is instance of parent class or subclass

For example,

public class A{...}

public class B extends A{...}

A a;
if(...) a = new A();
else a = new B();

Then, I want check if a is A or B . Is there any way to do this?

Check the type of object with instanceof take a look at the following

if(a instanceof B) {
    // the object is of sub class
} else {
    // the object is of super class
}

you can check whether an instance is a type of a class by following way

 if (a instanceof A) {
    //...
} else {
    //...
}

Renuka Fernando is correct, but you have to be careful here. Because of how objects are set up in memory, if your object is declared as a super class, but then initialized to one of its children, like so:

A a = new B();

Then the following code will always says " I'm an A! ":

if(a instanceof A)
    System.out.println("I'm an A!");
else
    System.out.println("I'm a B!");

That is because a is an A and a B at the same time, so if you were trying to see if a was a B , then you would have to put in further checks.

You can use getClass() method of the object instance..

class K {

} 
class P extends K {
}

public class A {
    public static void main(String args[]) {
        K k = new K();
        K p = new P();
        P p1 = new P();

        System.out.println(p.getClass().getName());
        System.out.println(p1.getClass().getName());
        System.out.println(k.getClass().getName());

    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM