This is what I think you're saying:
public class A {
}
public class B extends A {
}
later in code:
A apple = new A();
B banana = new B();
Here are some options that you may find useful:
if (apple.getClass() == A.class) { // Found an A }
if (banana.getClass() == A.class) { // This is not an A, won't get here. }
if (apple instanceof A) { // This is definitely an A }
if ((apple instanceof A) && (!(apple instanceof B))) { // It's an A but not a B }
Regarding the last option, you write the following:
Sure, I can write something like
"object instaceof A && !(object
instance of B)" but this is a very
poor design since I'll need to change
the code every time I add new
subclasses to A. Better alternatives?
Polymorphism almost always helps us here. Your point about changing code every time you add a subclass is exactly the kind of symptom that you should recognize as standard object-oriented design evolution. Think about the behavior that you are trying to produce. Can you push that into the class itself rather than delegating it to an outside provider looking in that has to deduce what class it's currently working on?
Without more information, I can't give too much guidance but here's a fairly straightforward example:
// Instead of this
if (apple.isClassA()) { // run class A code
} else if (apple.isClassB()) { // run class B code
// And so forth
}
Modify the design to become more like this:
public class A {
public void executeCommand() {
// run class A code
// This method knows that it's definitely an A, not a B
}
}
public class B extends A {
public void executeCommand() {
// run class B code
// This method knows that it's a B (and, therefore, an A as well).
}
}
Where later in the execution code, you replace your previous if test with:
apple.executeCommand();
banana.executeCommand();
Admittedly, this is a nearly trivial object-oriented design review but it may shake something loose and help you with your subclassing problem.