Java: Getting the subclass from a superclass list -
i'm new java , have 2 questions following code:
class animal { } class dog extends animal { } class cat extends animal { } class rat extends animal { } class main { list<animal> animals = new arraylist<animal>(); public void main(string[] args) { animals.add(new dog()); animals.add(new rat()); animals.add(new dog()); animals.add(new cat()); animals.add(new rat()); animals.add(new cat()); list<animal> cats = getcertainanimals( /*some parameter specifying want cat instances*/ ); } }
1) there way either dog or cat instances aminal list? 2) if yes, how should correctly build getcertainanimals method?
animal = animals.get(i); if (a instanceof cat) { cat c = (cat) a; } else if (a instanceof dog) { dog d = (dog) a; }
nb: compile if not use instanceof
, allow cast a
cat
or dog
, if a
rat
. despite compiling, classcastexception
on runtime. so, make sure use instanceof
.
Comments
Post a Comment