lundi 27 juillet 2020

How to display methods from a random element in Arraylist?

I know how to get a random element from ArrayList, but what I don't know is how to also display only 1 element's methods. For example, I have two subclasses with a few methods that are very basic (they basically just print some stuff), and the ArrayList is in the superclass.

This is my code with the Cat and Dog being subclasses. Now the code prints one of them but methods from both classes are displayed. If the program picks Dog for example, then I want only the results from Dog's noise() and furr() to be displayed. How could I do this?

ArrayList<Animal> an = new ArrayList<>();
        an.add(new Cat());
        an.add(new Dog());

       for (Animal a : an) { 
        a.noise();
        a.furr();
    }
   
    int randomIndex = (int) (Math.random() * an.size());
    System.out.println( "The animal: " +  an.get( randomIndex ));



Aucun commentaire:

Enregistrer un commentaire