How to determine an object's class?
If class `B` and class `C` extend class `A` and I have an object of type `B` or `C`, how can I determine of which type it is an instance?
Matthew F.
answered 04/05/19
Professional Software/ Web Developer Specializing in Java
public class A {...}
public class B extends A {...}
public class C extends A {...}
...
public static void main(String[] args) {
ArrayList<A> aList = new ArrayList<A>();
aList.add(new B());
aList.add(new C());
for(A a: aList) {
if(a instanceof A) {
System.out.println("Object is instance of class A!");
}
}
}
Output
Object is instance of class A!
Object is instance of class A!
Logic is fairly straightforward. instanceof keyword in Java does just that.
Still looking for help? Get the right answer, fast.
OR
Find an Online Tutor Now
Choose an expert and meet online.
No packages or subscriptions, pay only for the time you need.