Java for Programmers:
Lab 9
Create 2 subclasses of animal, a Dog and a Cat. They do
not need any methods or data of their
own yet. They should suppply a constructor that passes an
appropriate genus and species to the
superclass [Animal] constructor.
Create a new class called AnimalRunner which has a main
method. In the main method of
AnimalRunner, you should create a new Array of Animal type.
Add 3 elements to it: a Cat, a Dog
and a Person.
Iterate through the array and print out the genus and species
of each animal.
package com.annedirkse;
public class Dog extends Animal {
public Dog() {
super("canis", "familiaris");
}
}
package com.annedirkse;
public class Cat extends Animal {
public Cat() {
super("felis", "domesticus");
}
}
package com.annedirkse;
public class Person extends Animal {
private String name;
private int age;
private int hairColor;
static final int HAIR_COLOR_BROWN = 1;
static final int HAIR_COLOR_BLONDE= 2;
static final int HAIR_COLOR_RED = 3;
static final int HAIR_COLOR_BLACK = 4;
static final int HAIR_COLOR_GRAY = 5; public void setHairColor(int hairColor) { this.hairColor = hairColor; } public int getHairColor() { return hairColor; }
public void setAge(int age) { this.age = age; }
public void setAge(String age) { Integer ageInt = new Integer(age); this.age = ageInt.intValue(); }
public void setName(String name) { this.name = name; } public String getName() { return name; } public int getAge() { return age; } public Person(String name) { super("homo", "sapiens"); this.name = name; }
}
package com.annedirkse;
public class AnimalLister {
public static void main(String[] args) {
Animal[] animals = new Animal[4]; Person p = new Person("Anne"); Cat c = new Cat(); Dog d = new Dog();
Animal emporerPenguin = new Animal("Aptenodytes", "forsteri"); // You can still create a Generic Animal
animals[0] = p; animals[1] = c; animals[2] = d; animals[3] = emporerPenguin;
for (int i = 0; i < animals.length; i++) { Animal animal = animals[i]; System.out.println(animal.getGenus()); System.out.println(animal.getSpecies()); } }
}
|