I want to check the type of a subclass in Java. Here's the pseudocode I want to achieve:
public class Brown { ... }
class Poo extends Brown { ... }
class Brownie extends Brown { ... }
...
ArrayList<Brown> brownThings = new ArrayList<Brown>();
...
for (Brown i: brownThings)
// if i is a brownie eat
// else dispose of
You can use instanceof key word
if (i instanceof Brownie ) {
// do something
}
That exactly checks the instance type.
You can use instaceof
operator. For example:
if (i instanceof Brownie) {
eat(i);
} else {
dispose(i);
}
instaceof
opertaor check if the type of an object is an instance of a class or a class that extends or implements the specified type.
You can read more in Java tutorial, operators . Also see question What is the instaceof operator used for .
instanceof can handle that just fine.
This should do:
for (Brown i: brownThings) {
if (i instanceof Brownie) {
//eat
}
}
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.