Reputation: 81
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?
Upvotes: 2
Views: 4592
Reputation: 2668
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
}
Upvotes: 4
Reputation: 146
you can check whether an instance is a type of a class by following way
if (a instanceof A) {
//...
} else {
//...
}
Upvotes: 3
Reputation: 1129
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());
}
}
Upvotes: -1
Reputation: 2216
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.
Upvotes: 0