0

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
Coffee Maker
  • 1,543
  • 1
  • 16
  • 29

4 Answers4

4

You can use instanceof key word

if (i instanceof Brownie ) {
    // do something
  }

That exactly checks the instance type.

Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
1

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.

Community
  • 1
  • 1
PhoneixS
  • 10,574
  • 6
  • 57
  • 73
0
instanceof can handle that just fine.
0

This should do:

for (Brown i: brownThings) {
    if (i instanceof Brownie) {
        //eat
    }
}
Pieter
  • 895
  • 11
  • 22