java - Instance of an extended class given a collection of super class -


i looking advice on how approach following scenario:

let's have array of type , in array there objects of various types extend said type. example: have super class pet, make pet array, , put various objects of dog, cat, , fish classes , put them in array. now, each type of pet has own fields , methods, naturally.

this issue comes play. want loop through array , search specific object , call 1 of methods. building off previous example, want search dog name of "benny". once find it, want call benny's gethairlengthmethod. however, if i'm iterating through collection of various pet types, cannot call pet[index].gethairlength since not pets have method(only dogs do).

any tips?

1) can cast "pet" (superclass) "dog" (subclass). whether should question, "can".

2) if you're getting classcastexception ... you've done wrong. you're saving wrong object or wrong type. we'd need see code troubleshoot.

3) 1 solution save "pets" list, have if/else block:

  pet p = pets[i];   if (p instanceof dog)      ...   else if (p instanceof cat)      ... 

4) solution save same object many distinct lists makes sense:

  list<pet> pets = new arraylist<pet>();   list<dog> dogs = new arraylist<dog>();   ...   dog fido = new dog (...);   pets.add(fido);   dogs.add(fido); 

this way, can:

a) search "dogs" more efficiently (you won't have deal "cats" or "goldfish")

b) don't have cast anything

c) still maintain complete flexibility aggregate "pets".


Comments

Popular posts from this blog

c++ - OpenCV Error: Assertion failed <scn == 3 ::scn == 4> in unknown function, -

php - render data via PDO::FETCH_FUNC vs loop -

The canvas has been tainted by cross-origin data in chrome only -