Wednesday 8 December 2010

Chapter 10 Test

Chapter Ten Test


Mr. Daly, I would like to state that Mike Silber has helped me a lot in this test and I was only able to complete some of the tasks thanks to his help. 
1. Open a clean version of "foxes-and-rabbits-v2".


DONE
Your task is to modify the project so that gender can be taken into account as animals breed "foxes-and-rabbits-v3".

2. To do this you should create an Interface Gender..


The Gender interface has been created



public interface Gender
{


  public boolean isMale(); 
  public boolean isFemale();
}



public interface Gender
{

  public boolean isMale();
  
  public boolean isFemale();
}


3. The Animal class should be modified to implement Interface Gender.


public abstract class Animal implements Gender


 In order to do this you will need to add a field and to modify the constructor.




 Do not change the parameter list of the constructor. Each time an Animal is constructed a random gender is assigned. The probability of male or female is equal.


THIS IS MY NEW ANIMAL CLASS:

import java.util.List;
import java.util.Random;


/**
 * A class representing shared characteristics of animals.
 * 
 * @author David J. Barnes and Michael Kolling
 * @version 2008.03.30
 */
public abstract class Animal implements Gender
{
    // Whether the animal is alive or not.
    private boolean alive;
    // The animal's field.
    private Field field;
    // The animal's position in the field.
    private Location location;
    
    private boolean gender;
    
    /**
     * Create a new animal at location in field.
     * 
     * @param field The field currently occupied.
     * @param location The location within the field.
     */
    public Animal(Field field, Location location)
    {
        alive = true;
        this.field = field;
        setLocation(location);
        Random Gender = new Random();
        gender = Gender.nextBoolean();
    }
    
    /**
     * Make this animal act - that is: make it do
     * whatever it wants/needs to do.
     * @param newAnimals A list to add newly born animals to.
     */
    abstract public void act(List<Animal> newAnimals);


    /**
     * Check whether the animal is alive or not.
     * @return true if the animal is still alive.
     */
    public boolean isAlive()
    {
        return alive;
    }


    /**
     * Indicate that the animal is no longer alive.
     * It is removed from the field.
     */
    public void setDead()
    {
        alive = false;
        if(location != null) {
            field.clear(location);
            location = null;
            field = null;
        }
    }


    /**
     * Return the animal's location.
     * @return The animal's location.
     */
    public Location getLocation()
    {
        return location;
    }
    
    
    
    /**
     * Return the animal's field.
     * @return The animal's field.
     */
    public Field getField()
    {
        return field;
    }
    
    /**
     * Place the animal at the new location in the given field.
     * @param newLocation The animal's new location.
     */
    public void setLocation(Location newLocation)
    {
        if(location != null) {
            field.clear(location);
        }
        location = newLocation;
        field.place(this, newLocation);
    }
    
    public boolean isMale()
    {
        return gender;
    }
    
    public boolean isFemale()
    {
        if(gender)
        return false;
    else return true;
    }
}





4. Test your implementation by creating some rabbits (male and female) and foxes (male and female), then checking that isMale() and isFemale() work. Does the frequency of males and females seem to be about 50% in the population.




THIS WORKS! 
The frequency is almost 50% since there are a little more males than females at the end.Show your code to the supervisor.


I was able to do this thanks to the Count class I created. Here is the code for it:



public class Count
{
   static int males;
   static int females;


   /**
    * Constructor for objects of class Count
    */
   public Count()
   {
       males = 0;
       females = 0;
   }


   static void count()
   {
       System.out.println(males + " :: " + females);
   }
   
   static void addMale()
   {
       males++;
   }
   
   static void addFemale()
   {
       females++;
   }
   
   static void removeMale()
   {
       males--;
   }
   
   static void removeFemale()
   {
       females--;
   }
}



The simulation should now work exactly as before because information regarding gender is not used.


5. Working only with class Rabbit: modify the canBreed() method so that it only allows a Rabbit to breed if it is next to another Rabbit of the opposite sex.

return ( (age >= BREEDING_AGE)  && foundOppositeSex);

hints....

foundOppositeSex is a local boolean variable initially set to false

foundOppositeSex is set to true if a Rabbit of the opposite sex is found in one of the adjacent locations in the field




6. Now run your simulation. How does the introduction of gender impact the changing populations? Make a quantitative comparison of V2 and V3.


7. Given what you have learned from V3, describe one way of extending the simulation in "V4". What hypothesis will you be testing with V4?


In v4, in order to create a more accurate simulation of the "circle of life" and the survival of the rabbits and foxes in nature, we should create a Disease class which randomly chooses either a fox or a rabbit and kills it due to disease. At the moment the simulation assumes that the rabbits only die because of old age or being eaten by a fox which is false, they may also die of diseases. The simulation also assumes that foxes only die due to hunger and old age, which is also not true. Just as any animal on earth they might die due to disease.


Also, we may want to include food for rabbits since at the moment, the simulation assumes that the rabbits can survive without food which is completely WRONG! Therefore, we might want to create an Herb or a Grass/ Vegetable class which is eaten by the rabbits.

Wednesday 17 November 2010

Barnes and Kolling Chapter Ten Questions

Barnes and Kolling Chapter Ten Questions


1
Create a Simulator object using the constructor without parameters and you should see the initial state of the simulation as shown in text Figure 10.2. The more numerous rectangles represent  the rabbits.
Does the number of foxes change if you call the simulateOneStep() method just once?

The number of foxes changes when the method is called
2
Does the number of foxes change on every step?
What natural processes do you think we are modelling that cause the number of foxes to increase or decrease?

The number of foxes changes every time the method is called. Foxes increase: reprosduction
Foxes decrease: death
3
Call the simulate() method to run the simulation continuously for for a significant number of steps, such as 50 or 100.
Do the numbers of foxes and rabbits increase of decrease at similar rates?

The number of rabbits decreases as foxes increase. 
4
What changes do you notice if you run the simulation for a very long time, say 500 steps?
You can use the runLongSimulation()method to do this.

After many steps the rabbits are all gone! 
5
Use the reset() method to restore the starting state of the simulation, and then run it again.
Is an identical simulation run this time?
If not, do you see broadly similar patterns emerging anyway?

This time, all the foxes died and the rabbits lived. There is no specific pattern and it is unknown who will survive!
6
If you run a simulation for long enough, do all the foxes, or all the rabbits ever die off completely?
If so, can you pinpoint any reasons why that might be occuring?

The screen is never empty, either all the foxes disappear or all the rabbits die. 
7
Do you feel that omitting gender as an attribute in the Rabbit class is likely to lead to an inaccurate simulation?
Yes since the same gender cannot reproduce and therefore the simulation is not accurate
8
Are there other simplifications that you feel are present in our implementation of theRabbit class, compared with real life?
Do you feel that these could have a significant impact on the accuracy of the simulation?

There is a certain  age rabbit must get to in order to reproduce just like real life. 
9
Experiment with the effects of altering some or all of the values of the static variables in the Rabbit class.
For instance, what effect does it have on the fox and rabbit populations if the breeding probability of rabbits is much higher or lower?

When increasing the reproduction probability the rabbits reproduced very fast and therefore the foxes survived since they had food. When reproduction prob was low, the foxes all diead since they had no food.
10
As you did for rabbits, assess the degree to which we have simplified the model of foxes and evaluate whether you feel the simplifications are likely to lead to an inaccurate simulation.
It is similar to real life in its hunting methods and the fact that it has a hunger field.
11
Does increasing the maximum age for foxes lead to significantly higher numbers of foxes throughout the simulation, or is the rabbit population more likely to be reduced to zero as a result?
No, it just kills all the rabbits in a faster rate.
12
Experiment with different combinations of settings (breeding age, maximum age, breeding probability, litter size, etc.) for foxes and rabbits.
Do species always disappear completely in some configurations?
Are there configurations that are stable?

it is stable when there is a huge number of steps. None of the species die.
13
Experiment with different sizes of field. (You can do this by using the second simulator constructor.)
Does the size of the field effect the likelihood of the species surviving?

Yes. since there is more space so rabbits or foxes dont just disappear.
14
Currently a fox will eat at most one rabbit at each step. Modify the findFood() method so that rabbits in all adjacent locations are eaten at a single step.
Assess the impact of this change on the results of the simulation.


private void findFood()
    {
        List<Location> adjacent = field.adjacentLocations(location);
        Iterator<Location> it = adjacent.iterator();
        while(it.hasNext()) {
            Location where = it.next();
            Object animal = field.getObjectAt(where);
            if(animal instanceof Rabbit) {
                Rabbit rabbit = (Rabbit) animal;
                if(rabbit.isAlive()) { 
                    rabbit.setDead();
                    foodLevel = RABBIT_FOOD_VALUE;
                    // Remove the dead rabbit from the field.
                    
                }
15
When a fox eats a large number of rabbits at a single step, there are several different possibilities as to how we can model its food level. If we add all the rabbit's food values the fox will have a very high food level, making it unlikely to die from hunger for a very long time.
Alternatively, we could impose a ceiling on the fox's foodlevel. This models the effect of a predator that kills prey regardless of whether it is hungry or not.
Assess the impacts of implementing this choice on the resulting simulation.
The effect of a predator killing prey regardles of whether its hungry or not could make the the simulation more realistic.
16
Modify the populate() method of Simulator to determine whether not setting an initail random age for foxes and rabbits is catastrophic.
if the initial age is not random the fox or rabbits could be to young to breed therefore causing the simulation to be completely unrealistic.
17
If an initail random age is set for rabbits but not for foxes, the rabbit population will tend to grow large, while the fox population remains very small.
Once the foxes do become old enough to breed, does the simulation tend to behave again like the original version?
What does this suggest about the relative sizes of the initial populations and their impact on the outcome of the simulation?

It shows that the size of the initial population has affects the outcome in terms of who survives. 
18
When a rabbit moves to a free location, it is placed in the updated field only if there is not already a fox at that location.
What is the effect on the fox population if this constraint is removed?
Is the same constraint placed upon newly born rabbits?


19
Could two foxes ever try to move to the same location in the updated field?
If so, should an attempt be made to avoid this situation?

Yes, In real life, foxes are able to share the hunted prey therefore this situation shouldnt be avoided and should also be fixed into a more realistic simulation.
20
Identify the similarities and differences between the Fox and the Rabbit classes.
Make separate lists of the fields, methods and constructors, and distinguish between the class variables (static fields) and instance variables.

SIMILARITIS: isAlive boolean field, the age integer field, a location field,  breeding age,  max age, a breeding probability,
  constructors are  the same, except the fox's food level constructor. 
methods:  IsDead(), giveBirth(), setDead(), incrementAge(), breed(), canBreed(), setLocation(), and getLocation(). 
21
Candidate methods to be placed in a superclass are those that are identical in all subclasses.
Which methods are truly identical in the Foxand Rabbit classes?
In reaching a conclusion, you might like to consider the effect of substituting the values of class variables into the bodies of the methods that use them.

IsDead(), giveBirth(), setDead(), incrementAge(), breed(), canBreed(), setLocation(), and getLocation(). These are completley identical.
22
In the current version of the simulation, the values of all similarly named class variables are different.
If the two values of a particular class variable (BREEDING_AGE, say) were identical, would it make any difference to your assessment of which methods are identical?


23
What sort of regression-testing strategey could you establish before undertaking the process of refactoring on the simulation?
Is this something that you could conveniently automate?

Ma ze Regression Testing?
24
Create the Animal superclass in your version of the project. Make the changes dicussed in the text. Ensure that the simulation works in a similar manner as before.

public abstract class Animal
{
    // Whether the animal is alive or not.
    private boolean alive;
    // The animal's field.
    private Field field;
    // The animal's position in the field.
    private Location location;
    
    /**
     * Create a new animal at location in field.
     * 
     * @param field The field currently occupied.
     * @param location The location within the field.
     */
    public Animal(Field field, Location location)
    {
        alive = true;
        this.field = field;
        setLocation(location);
    }
    
    /**
     * Make this animal act - that is: make it do
     * whatever it wants/needs to do.
     * @param newAnimals A list to add newly born animals to.
     */
    abstract public void act(List<Animal> newAnimals);


    /**
     * Check whether the animal is alive or not.
     * @return true if the animal is still alive.
     */
    public boolean isAlive()
    {
        return alive;
    }


    /**
     * Indicate that the animal is no longer alive.
     * It is removed from the field.
     */
    public void setDead()
    {
        alive = false;
        if(location != null) {
            field.clear(location);
            location = null;
            field = null;
        }
    }


    /**
     * Return the animal's location.
     * @return The animal's location.
     */
    public Location getLocation()
    {
        return location;
    }
    
    /**
     * Return the animal's field.
     * @return The animal's field.
     */
    public Field getField()
    {
        return field;
    }
    
    /**
     * Place the animal at the new location in the given field.
     * @param newLocation The animal's new location.
     */
    public void setLocation(Location newLocation)
    {
        if(location != null) {
            field.clear(location);
        }
        location = newLocation;
        field.place(this, newLocation);
    }
    
}

25
How has using inheritance improved the project so far?
Discuss.

Inheritance has improved it by reducing duplicate codes in the fox and in the rabbit class. using inheritance makes the project easier to understand and also more efficient. 
26
Although the body of the loop in Code 10.6 no longer deals with the Fox and Rabbit types, it still deals with the Animal type.
Why is it not possible for it to treat each object in the collection simply using the Object type?

27
Is it necessary for a class with one or more abstract methods to be defined as abstract?

If you are not sure, experiment with the source of the Animal class in the foxes-and-rabbits-v2 project.

28
Is it possible for a class that has no abstract methods to be defined as abstract?

If you are not sure, change act() to be a concrete method in the Animal class by giving it a method body with no statements.
Yes it is.
29
Could it ever make sense to define a class as abstract if it has no abstract methods? Discuss this.
Yes, since abstract classes have many purposes that may be needed even if you do not use abstract methods. 
30


31


32
Which of the other simulation classes do not need to be aware of whether they are specifically dealing with foxes or rabbits? Could they be rewritten to use the Animal class instead? Would there be any particular benefits in doing this?/P>
perhaps the location and field classes.
33
Review the overriding rules for methods and fields discussed in Chapter 9. Why are they particularly significant in our attempts to introduce inheritance into this application?
Because not knowing how to correctly override methods when using abstract classes is catastrophic.
34
The changes made in this text section have removed the dependence (couplings) of the simulateOneStep() method to the Fox and Rabbit class. The Simulator class however, is still coupled to Fox and Rabbit, because these classes are referenced in the populate() method. There is no way to avoid this: when we create Animal instances, we have to specify exactly what kind of animal to create. This could be improved by splitting the Simulator into two classes: one class Simulator, which runs the simulation and is completely decoupled from the concrete animal classes, and one class, PopulationGenerator (created and called by the simulator), which create the population. Only this class is coupled to the concrete animal classes, making it easier for a maintenance programmer to find places where change is necessary when the application is extended. Try implementing this refactoring step. The PopulationGenerator class should also define the colors for each type of animal.>

35
The canBreed() method of Fox and Rabbit are textually identical, yet we chose not to move them to the Animal class. Why is this? Try moving the methods from Fox and Rabbit and making them protected. Is there any way to make the resulting classes compile and, even if there is, does the resulting simulation work as it should? How can you tell?
Since the fox breeding age and the rabbit breeding age is different, we cannot intialize one value to it in a superclass therefore we cannot move the canBreed method to a superclass.. this would cause an incorrect simulation. 
36
Using your latest version of the project (or the foxes-and-rabbits-V2 project in case you have not done all the exercises), move the canBreed() method from Fox and Rabbit to Animal and rewrite it as shown in code 10.8. Provide appropriate versions of getBreedingAge() in Fox and Rabbit. Are those changes sufficient to recompile the project? If not, what is missing from the Animal class?ced any new participant types.

37
Move the incrementAge() method from Fox and Rabbit to Animal by providing an abstract getmaxAge() method in Animal and a concrete version in Fox and Rabbit.

38
Can the breed() method be moved to Animal?

If so, make this change.
>

39
In the light of all the changes you have made to these three classes, reconsider the visibility of each method and make any changes you feel are appropriate.

40
Was is possible to make these changes without having any imapct on any other classes in the project? If so, what does this suggest about the degrees of encapsulation and coupling that were present in the original version?

41
Define a completely new type of animal for the simulation as a subclass of Animal. You will need to decide what sort of impact its existence will have on the existing animal types. For instance, your animal might compete with foxes as a predator on the rabbit population, or your animal might prey on foxes but not on rabbits. You will probably find that you need to experiment quite a lot with the configuration settings you use for it. You will need to modify the populate() method to have some of your animals created at the start of a simulation. You should also define a new color for your new animal class. You can find a list of pre-defined color names on the API page documenting the Color class in the java.awt package.

42
Introduce the Actor class into your simulation. Rewrite the simulateOneStep() method in Simulator to use Actor instead of Animal. You can do this even if you have not introduced any new participant types.

Does the Simulator class compile? Or is there something else that is needed in the Actor class?

43
Redefine the abstract class Actor in your project as an interface.

Does the simulation still compile?

Does it run?

44
Are the fields in the following interface static fields or instance fields?

public interface Quiz
{
int CORRECT = 1;
int INCORRECT = 0;
...
}

What visibility do they have?

45
What are the errors in the following interface?

public interface Monitor
{
private static final int THRESHOLD = 50;
public Monitor (int initial);
public int getThreshold()
{
return THRESHOLD;
}
...
}

46
Add a non-animal actor to the simulation. For instance, you could introduce a Hunter class with the following properties.

Hunters have no maximum age and neither feed nor breed. At each step in the simulation, a hunter moves to a random location anywhere in the field and fires a fixed number of shots into random target locations around the field. Any animal in one of the target locations is killed.

Place just a small number of hunters in the field at the start of the simulation. Do the hunters remain in the simulation throughout or do they ever disappear?

If they do disappear, why might that be, and does that represent realistic behavior?

What other classes required changing as a result of introducting hunters?

Is there a need to introduce further decoupling to the classes?

47
Which methods do ArrayList and LinkedList have that are not defined in the List interface?

Why do you think that these methods are not included in List?

48
Read the API description for the sort methods of the Collections class in the java.util package.

Which interfaces are mentioned in the descriptions?

49
Investigate the Comparator interface.
Define a simple class that implements Comparator.
Create a collection containing objects of this class and sort the collection.

50
Make the changes described in the text: rename the class SimulatorView to AnimatedView and implement the SimulatorView interface.

Make sure that, in class Simulator, the name AnimatedView is used only one single time (when the view object is created).

At all other places, the interface name SimulatorView should be used.

51
Implement a new class TextView that implements SimulatorView. TextView provides a textual view of the simulation. After every simulation step, it prints out one line in the form

Foxes: 122 Rabbits: 265

Use TextView instead of AnimatedView for some tests. (Do not delete the AnimatedView classes. We want to have the ability to change between both views).

52
Can you manage to have both views active at the same time?

53
Can an abstract class have concrete (non-abstarct) methods?
Can a concrete class have abstract methods?
Can you have an abstract class without abstract methods?
Justify your answers

54
Look at the code below. You have five types (classes or interfaces) (U,G,B,Z, and X) and a variable of each of these types.

U u;
G g;
B b;
Z z;
X x;

The following assignments are legal (assume that they all compile)

u = z;
x = b;
g = u;
x = u;

The following assignments are all illegal (they cause compiler errors)

u = b;
x = g;
b = u;
z = u;
g = x;

What can you say about the types and their relationships? (What relationship are they to each other?)

55
Assume you want to model people in a university to implement a course management system. There are different people involved: staff members, students, teaching staff, support satff, tutors, technical support staff, and student technicians.

Tutors and student technicians are intersting: tutors are students who have been hired to do some teaching, and student technicians are students who have been hired to help with technical support.

Draw a type hierarchy (classes and interfaces) to represent this situation.

Indicate which types are concrete classes, abstract classes and interfaces.

56
If you test the foxes-and-rabbits project carefully, you may discover that it has a flaw: it runs more and more slowly over time. (To test this, time some executions. For example, run and time it with 500, 1000, 2000, and 3000 steps.)

Find the source of the problem and fix it.

What debugging techniques did you use?

57
Sometimes class/interface pairs exist in the Java standard library that define exactly the same methods. Often the interface name ends with Listener and the class name ends with Adapter. An example is PrintJobListener()and PrintJobAdapter().

The interface defines some method signatures, and the adapter class defines the same methos, each with an empty method body.

What might the reason be for having them both?

58
The collection library has a class named TreeSet, which is an example of a sorted set. Elements in this set are kept in order. Read the description of this class carefully, and then write a class Person that can be inserted into a TreeSet, which will then sort the Person objects by age.