I have a stack of Objects, in this stack I push ClassA and ClassB objects. I have a method which must return objects from this stack
public Object method(Stack s){
ClassA a = new ClassA();
stack.push(a);
ClassB b = new ClassB();
stack.push(b);
while(stack has two elements) stack.pop();
return stack.pop()// I return the last element
}
the problem is: when I call this method instanceof doesn't work, it can't tell anymore ClassA from ClassB
Object o = method(s);
if ( o instanceof ClassA){
//do something
} else if (o instanceof ClassB) {
//do something else
}
Inside method(Stack s) instanceof works, outside doesn't, but the toString() method works fine, it return the proper String for each class.