0

I have an abstract superclass called C and multiple subclasses of it: SubC1, SubC2, ... Now I have a collection of the superclass C and I want to iterate over it, but do something different depending on which subclass it is. Here is the pseudo-code:

abstract class C{}
class SubC1 extends C{}
class SubC2 extends C{}

...

for(C c : cs){
    if(c is a SubC1){
    //do one thing
    }
    if(c is a SubC2){ 
    //do another
    }
}

However Im not really sure how to set up the if conditionals. My first thought was to use instanceof but then I realized that it doesnt work for downcasts. Then I considered adding a String field to C and make each subclass define it and base my conditionals around that, but that seems clunky. I also considered trying to use process of elimination by forcing a downcast and catching the ClassCastExceptions, but that is also clunky and seems kinda dangerous. So how can I get what I want without having stupid code?

Edit: I forgot to add that it would not make sense for me to add a doSomething() function in C and just override it.

Edit 2: For some reason I thought doing c instanceof SubC1 caused a compiler error. Now that I realize it didnt I have my answer.

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
David says Reinstate Monica
  • 19,209
  • 22
  • 79
  • 122

1 Answers1

3

Have an abstract method doSomething in C and override it in all of your subclasses, then call C#doSomething

Zim-Zam O'Pootertoot
  • 17,888
  • 4
  • 41
  • 69