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
}
A a = new B(), will instanceof A be confused? is the output true? becuase B is derived from A.you can check whether an instance is a type of a class by following way
if (a instanceof A) {
//...
} else {
//...
}
a refers to a B object, then a instanceof B is still true, because B extends A. So you'd first have to check for a instanceof B.A a = new B(), then instanceof B and instanceof A are both true?A a = new A(), then only instanceof A is true. this is why I have to check B first. Thank you .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());
}
}
instanceof functionality for a reason. Java reflection should only be used in a few special cases and in other cases is considered bad programming practice, because of the security vulnerabilities that can arise. Obvious your solution above works and does not do anything nasty, but you are strictly avoiding a feature that was made for this exact purpose.
instanceofmethod in java to verify whether certain obj is a instance of a class..... If you want to know the type after the condition, instanceof is what you need.