Creating methods that work with instances of different subclasses
After we declare all the new classes, we will create the following two methods that receive a VirtualAnimal
instance as an argument, that is, a VirtualAnimal
instance or an instance of any subclass of VirtualAnimal
. Each method calls a different instance method defined in the VirtualAnimal
class: printAverageNumberOfBabies
and printAsciiArg
. The code file for the sample is included in the java_9_oop_chapter_07_01
folder, in the example07_02.java
file.
void printBabies(VirtualAnimal animal) { animal.printAverageNumberOfBabies(); } void printAsciiArt(VirtualAnimal animal) { animal.printAsciiArt(); }
Then the following lines create instances of the next classes: Cockatiel
, VirtualDomesticRabbit
, and MaineCoon
. The code file for the sample is included in the java_9_oop_chapter_07_01
folder, in the example07_02.java
file.
Cockatiel tweety = new Cockatiel(3, "White", "Tweety"); VirtualDomesticRabbit bunny = new VirtualDomesticRabbit...