Herança e Composição/Aplicação Simples com Animais (não específicos) e Gatos

From Wiki**3

< Herança e Composição

Classe Animal

O animal modelado pela classe Animal tem um nome e uma idade (e respectivos métodos de acesso). Assume-se que todos os animais respiram (método breathe), encontram outros animais (método meet) e morrem (método die). Estes métodos representam as suas acções pela impressão de uma cadeia de caracteres apropriada. A class Animal redefine ainda o método toString (para apresentação específica de instâncias da classe).

 1   public class Animal {
 2   
 3     /** The age of the animal. */
 4     private int _age;
 5   
 6     private String _name;
 7   
 8     public Animal(String name, int age) {
 9       _name = name;
10       _age  = age;
11     }
12   
13     public int getAge() { return _age; }
14     public void setAge(int age) { _age = age; }
15   
16     /**
17      * @return the name of the animal.
18      */
19     public String getName() { return _name; }
20     public void setName(String name) { _name = name; }
21   
22     /**
23      * How does an animal breathe?
24      */
25     public void breathe() {
26       System.out.println("Animal " + this + " is breathing.");
27     }
28   
29     /**
30      * An animal meets another animal.
31      * @param a the other animal
32      */
33     public void meet(Animal a) {
34       System.out.println("Animal " + this + " met " + a + ".");
35     }
36   
37     public void die() {
38       System.out.println("Animal " + this + " is dead, dead, dead!");
39     }
40   
41     public String toString() {
42       return _name + " (" + _age + " years old)";
43     }
44   
45   }

Classe Test (primeira versão)

Nesta aplicação, são criados algumas instâncias da classe Animal. Estas instâncias são depois percorridas e, para cada uma, executada a sequência "de vida do animal" correspondente a respirar, encontrar outro animal, respirar novamente e, finalmente, morrer.

 1   public class Test {
 2   
 3     public static void main(String args[]) {
 4       Animal animals[] = {
 5         new Animal("Tareco", 2),
 6         new Animal("Piloto", 20),
 7       };
 8       for (int ax = 0; ax < animals.length; ax++) {
 9         System.out.println("======" + animals[ax] + "======");
10         animals[ax].breathe();
11         int other = (int)(Math.random()*animals.length);
12         animals[ax].meet(animals[other]);
13         animals[ax].breathe();
14         animals[ax].die();
15       }
16     }
17   
18   }

Saída da Função Principal (segunda versão)

O quadro seguinte ilustra a execução da função main da classe Test.

 $ java Test
 ======Tareco (2 years old)======
 Animal Tareco (2 years old) is breathing.
 Animal Tareco (2 years old) met Piloto (20 years old).
 Animal Tareco (2 years old) is breathing.
 Animal Tareco (2 years old) is dead, dead, dead!
 ======Piloto (20 years old)======
 Animal Piloto (20 years old) is breathing.
 Animal Piloto (20 years old) met Tareco (2 years old).
 Animal Piloto (20 years old) is breathing.
 Animal Piloto (20 years old) is dead, dead, dead!

Classe Cat

A classe Cat é uma especialização da classe Animal, redefinindo alguns aspectos para o caso concreto do conceito gato.

 1   public class Gato extends Animal {
 2   
 3     public Gato(String name, int age) {
 4       super(name, age);
 5     }
 6   
 7     /**
 8      * How does an animal breathe?
 9      */
10     public void breathe() {
11       System.out.println("Gato " + this + " is breathing. Rrronnn, rrrroooonnn!!");
12     }
13   
14     /**
15      * An animal meets another animal.
16      * @param a the other animal
17      */
18     public void meet(Animal a) {
19       System.out.println("Gato " + this + " met " + a + " and scratched it.");
20     }
21   
22     public void die() {
23       System.out.println("Gato " + this + " is dead, but only temporarily...");
24     }
25   
26   }

Classe Test (segunda versão: com gatos)

Esta classe é idêntica à anterior, excepto pelo facto de agora existirem animais mais específicos no vector que é percorrido (neste caso particular, gatos, instâncias da classe Cat). Note-se que a alteração se limita a criar um gato em lugar de um animal genérico. Todo o restante processamento permanece inalterado.

 1   
 2   public class Test {
 3   
 4     public static void main(String args[]) {
 5       Animal animals[] = {
 6         new Cat("Tareco", 2),
 7         new Animal("Piloto", 20),
 8       };
 9       for (int ax = 0; ax < animals.length; ax++) {
10         System.out.println("======" + animals[ax] + "======");
11         animals[ax].breathe();
12         int other = (int)(Math.random()*animals.length);
13         animals[ax].meet(animals[other]);
14         animals[ax].breathe();
15         animals[ax].die();
16       }
17     }
18   
19   }

Saída da Função Principal (segunda versão)

O quadro seguinte ilustra a execução da função main da classe Test.

 $ java Test
 ======Tareco (2 years old)======
 Cat Tareco (2 years old) is breathing. Rrronnn, rrrroooonnn!!
 Cat Tareco (2 years old) met Tareco (2 years old) and scratched it.
 Cat Tareco (2 years old) is breathing. Rrronnn, rrrroooonnn!!
 Cat Tareco (2 years old) is dead, but only temporarily...
 ======Piloto (20 years old)======
 Animal Piloto (20 years old) is breathing.
 Animal Piloto (20 years old) met Tareco (2 years old).
 Animal Piloto (20 years old) is breathing.
 Animal Piloto (20 years old) is dead, dead, dead!