Open a new Eclipse (or using your favorite Java editor) Java Project Chapter9Exe
ID: 3816783 • Letter: O
Question
Open a new Eclipse (or using your favorite Java editor) Java Project Chapter9Exercise and create a class Animal.Give the Animal a single private int attribute hunger to hold how hungry the Animal is, a constructor that takesno arguments and sets this attribute to zero, and a method getHunger that returns it. Then write an abstractmethod talk that takes no arguments and returns nothing. (Recall that to make a method abstract, you putabstract at the beginning of the method signature (before public) and put a semicolon at the end of the signatureinstead of an opening brace.)
Try to compile this. You will get an error message about not having overridden the abstract method talk. Thiserror comes because the class Animal has an abstract method, but it is not declared to be an abstract class. Addabstract between public and class at the top of the file. This tells the computer that you intend Animal to be anabstract class. (Eclipse tries to help you with errors as you write code; pay attention to these hints andmessages; don’t just simply correct code without understanding what these errors are pointing to!)
Now check that Animal compiles. It does, but because Animal is an abstract class, you are not able to actuallycreate Animal objects. For that, we need to create a subclass.
Create a class Zebra. Make it a subclass of Animal by adding extends Animal to the end of the line giving the classname. Write a constructor for Zebra that takes no arguments. The entire body of this method should be super();
This calls the constructor for Animal. That constructor then sets its attribute hunger to 0. (Actually, Java willautomatically call the superclass constructor for us, but it’s a good habit to explicitly include a call to asuperclass constructor in each subclass constructor.)
If you try to compile at this point, you again get the error message about not having overridden the talk method.Oops! By inheriting from Animal, we promised to implement a talk method. Add a method talk that takes noarguments and returns nothing, just as promised in the Animal class. Make this method print the string “TheZebra quietly chews.”.
After writing talk, the project should compile. Create a Zebra object (you can do this by writing a main methodeither in the Zebra class or in a client class; the latter is preferred as it is not a good practice to add main methodto a pure Java class). Even though we did not declare any attributes within the code for Zebra, you see that ithas the int attribute inherited from Animal. Note the methods are able to invoke on the Zebra object – talk and
getHunger. Call both methods to verify that talk prints out the message about chewing and that getHunger returns 0.
There wouldn’t be any reason to write the abstract class Animal if we planned to write only one subclass. Writeanother subclass of Animal called Lion. As we did with Zebra, give it a constructor that takes no arguments andcalls the Animal constructor. Then write a talk method that just prints the message “Roar!”. Verify that thiscompiles and that both getHunger and talk work as intended in the Lion.
So far the hunger attribute does not do very much because it never changes from 0. Add a method timePasses toAnimal that increases the hunger attribute by one. (The idea is that this is called each unit of time so the animalsgradually get hungrier over time.) Lions are not content to quietly get hungrier, though. Override the timePasses
method in Lion with a method that increases hunger by 1 as above, but also prints the message “The Lion paceshungrily.” if its new value is at least 3. Note that you will not be able to access hunger directly because it is aprivate attribute of Animal. One solution is to change the access restrictions on hunger (e.g. make it public), butbetter is to access the attribute indirectly. To increase hunger, call the the timePasses method of Animal (usingsuper.timePasses();). Then, use the getHunger method to read the value of hunger.
Now that the animals can get hungry, we should have a way to feed them. Add a method feed to Animal that setshunger back to 0. Compile and create some animals to make sure they get hungrier and that hungry lions startpacing.
As a last step for the animals, let’s write a toString method. This is the method that is called automatically whenan object is printed (or a String representation is needed for some other reason). It must take no arguments andreturn a String. The classes already inherit such a method from the Object class (which you can verify by lookingin “inherited from Object” in the menu of methods). Since this toString method doesn’t give a very useful string,let’s override this method in Zebra and Lion with methods that return the class of the animal. (So the method inZebra returns “Zebra” and the one in Lion returns “Lion”.) Because the signature of your toString method needsto exactly match the signature of the one you’re overriding, you will need to explicitly make it public:
public String toString()
Once you complete this method, again compile, create some animals, and ensure that this works beforeproceeding.
Now let’s write some code to use our animal classes. Create a new class called Zoo. This one should not inheritfrom Animal since it doesn’t have an “is a” relationship with Animal. To start with, give your Zoo a single attributecalled cage which stores an Animal. Give it a constructor that takes an Animal object and stores it in thisattribute. Then write a method print that prints the message “The zoo contains a ” followed the animal’s type.(Since we’ve written a toString method, you can print an Animal object as if it were a String.) Printing the Zoo
should produce a message such as the following:The zoo contains a Lion
A zoo with only one animal isn’t going to attract many visitors. Therefore, we want to expand the Zoo class sothat it can accommodate multiple Animal objects. Rename cage to cage1 and add cage2 and cage3. Remove theargument to the constructor and just have it set all these variables to null. (That means that the variable doesn’treference any object.) Then create methods to set each of these (call them putInCage1, putInCage2, andputInCage3); the methods take an Animal object and set the appropriate variable. Then modify print to print anyof these that are not null in a format such as
The zoo contains the following:
Lion
Zebra
Since you don’t want to print a null reference, you’ll need to check each of them before printing it:
if(cage1 != null) {//print first animal} if(cage2 != null) {//print 2nd animal
} ...
Now, write Zoo methods timePasses, allTalk, and feedAll that call the corresponding method for each (non-null)animal in the zoo. Then, add another subclass of Animal; you’ll find this quite easy since the only methods youhave to write are the constructor, talk, and toString.
Explanation / Answer
Animal.java
package animal;
public abstract class Animal {
private int hunger;
public Animal() {
hunger = 0;
}
public int getHunger() {
return hunger;
}
public void timePasses()
{
hunger += 1;
}
public void feed()
{
hunger = 0;
}
abstract public void talk();
}
Zebra.java
package animal;
public class Zebra extends Animal{
public Zebra() {
super();
}
@Override
public void talk() {
System.out.println("The Zebra quietly chews.");
}
@Override
public String toString() {
// TODO Auto-generated method stub
return "Zebra";
}
}
Lion.java
package animal;
public class Lion extends Animal{
public Lion() {
super();
}
@Override
public void timePasses() {
super.timePasses();
if(getHunger()>=3)
System.out.println("The Lion paces hungrily.");
}
@Override
public void talk() {
System.out.println("Roar!");
}
@Override
public String toString() {
return "Lion";
}
}
AnimalDemo.java
package animal;
public class AnimalDemo {
public static void main(String[] args) {
Zebra zebra = new Zebra();
System.out.println("------------------ZEBRA---------------");
System.out.println("Who am I? " + zebra);
zebra.talk();
System.out.println("Hunger of Zebra: " + zebra.getHunger());
zebra.timePasses();
zebra.timePasses();
zebra.timePasses();
System.out.println("After passing time, hunger of Zebra: " + zebra.getHunger());
zebra.feed();
System.out.println("After feeding, hunger of Zebra: " + zebra.getHunger());
Lion lion = new Lion();
System.out.println(" ------------------LION---------------");
System.out.println("Who am I? " + lion);
lion.talk();
System.out.println("Hunger of Lion: " + lion.getHunger());
lion.timePasses();
lion.timePasses();
lion.timePasses();
System.out.println("After passing time, hunger of Lion: " + lion.getHunger());
lion.feed();
System.out.println("After feeding, hunger of Lion: " + lion.getHunger());
Rabbit rabbit = new Rabbit();
System.out.println(" -------------------ZOO------------------");
Zoo zoo = new Zoo();
zoo.putInCage1(zebra);
zoo.putInCage2(lion);
zoo.putInCage3(rabbit);
zoo.allTalk();
zoo.feedAll();
zoo.print();
}
}
Zoo.java
package animal;
public class Zoo {
private Animal cage1;
private Animal cage2;
private Animal cage3;
public Zoo() {
this.cage1 = null;
this.cage2 = null;
this.cage3 = null;
}
public void putInCage1(Animal animal)
{
this.cage1 = animal;
}
public void putInCage2(Animal animal)
{
this.cage2 = animal;
}
public void putInCage3(Animal animal)
{
this.cage3 = animal;
}
public void print()
{
System.out.println("The zoo contains the following:");
if(cage1 != null)
System.out.println(cage1);
if(cage2 != null)
System.out.println(cage2);
if(cage3 != null)
System.out.println(cage3);
}
public void timePasses()
{
if(cage1 != null)
cage1.timePasses();
if(cage2 != null)
cage2.timePasses();
if(cage3 != null)
cage3.timePasses();
}
public void allTalk()
{
if(cage1 != null)
cage1.talk();
if(cage2 != null)
cage2.talk();
if(cage3 != null)
cage3.talk();
}
public void feedAll()
{
if(cage1 != null)
cage1.feed();
if(cage2 != null)
cage2.feed();
if(cage3 != null)
cage3.feed();
}
}
Rabbit.java
package animal;
public class Rabbit extends Animal{
public Rabbit() {
super();
}
@Override
public void talk() {
System.out.println("The rabbit likes to eat carrots.");
}
@Override
public String toString() {
return "Rabbit";
}
}
OUTPUT:
------------------ZEBRA---------------
Who am I? Zebra
The Zebra quietly chews.
Hunger of Zebra: 0
After passing time, hunger of Zebra: 3
After feeding, hunger of Zebra: 0
------------------LION---------------
Who am I? Lion
Roar!
Hunger of Lion: 0
The Lion paces hungrily.
After passing time, hunger of Lion: 3
After feeding, hunger of Lion: 0
-------------------ZOO------------------
The Zebra quietly chews.
Roar!
The rabbit likes to eat carrots.
The zoo contains the following:
Zebra
Lion
Rabbit
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.