Java for Programmers:
Lab 10
Lab 10 --
Alter Animal. Declare Animal to be abstract.
Specify an abstract method in Animal called speak. Since
the method is abstract, Cat, Dog and
Person will have to provide an implementation for this method.
You will no longer be able to instantiate an Animal generically.
So the line:
Animal emporerPenguin = new Animal("Aptenodytes", "forsteri");
will have to go if you have included it.
To complete the lab:
Declare Animal abstract
- Define an absract method in Animal with the signature public void speak();
- Provide a method definition for speak with an implementation for each of Animal's
sub-classes (Dog, Cat and Person)
- Alter AnimalLister so that each animal's speak method is called during the
iteration through the array of Animals.
package com.annedirkse;
public abstract class Animal {
private String genus;
private String species;
public abstract void speak();
public String getGenus() { return genus; }
public void setGenus(String genus) {
this.genus = genus; }
public String getSpecies() { return species; }
public void setSpecies(String species) { this.species = species; }
public Animal(String genus, String species) { this.genus = genus; this.species = species;
}
}
package com.annedirkse;
public class AnimalLister {
public static void main(String[] args) {
Animal[] animals = new Animal[3];
Person p = new Person("Anne");
Cat c = new Cat();
Dog d = new Dog();
animals[0] = p;
animals[1] = c;
animals[2] = d;
for (int i = 0; i < animals.length; i++) {
Animal animal = animals[i];
animal.speak();
System.out.println(animal.getGenus());
System.out.println(animal.getSpecies());
}
}
}
package com.annedirkse;
public class Cat extends Animal {
public void speak() {
System.out.println("MEOW!");
}
public Cat() {
super("felis", "domesticus");
}
}
package com.annedirkse;
public class Dog extends Animal {
public void speak() {
System.out.println("WOOF!"); }
public Dog() { super("canis", "familiaris"); } }
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 void speak() { System.out.println("HULLO!"); } public Person(String name) { super("homo", "sapiens"); this.name = name; }
}
|