Using the matching class of isAssignableFrom() method in Java -


i have abstract class called pet lots of classes subclassing it.

public abstract class animal { }  public abstract class wildanimal extends animal { }  public abstract class pet extends animal {     public abstract void mynameis(); }  public class dog extends pet {     @override     public void mynameis() {         system.out.println("dog meat");     }      public void bark() {         system.out.println("woof");     } }  public class cat extends pet {     @override     public void mynameis() {         system.out.println("cheshire");     }      public void purr() {         system.out.println("purr");     } }     // somewhere else in project ...  list<animal> animals = new arraylist<animal>(); // lots of animals added by:  animalmoves(animals);  public void petmoves(list<animal> animals) { if (pet.class.isassignablefrom(animals.getclass())) {     // dog, cat, mouse, etc.     pet = (pet)pet; 

i want able call overridden mynameis() method each subclassed class, not abstract class' mynameis(). how so?

you don't need isassignablefrom check: parameter declared have type pet. obviously, class pet assignable has type pet, so, check return true.

to answer question: pet.mynameis() you asking.


Comments

Popular posts from this blog

c++ - llvm function pass ReplaceInstWithInst malloc -

java.lang.NoClassDefFoundError When Creating New Android Project -

Decoding a Python 2 `tempfile` with python-future -