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.








Monday, 15 November 2010

Chapter 9 Exercises

Barnes and Kolling Chapter Nine Questions


1
Open your last version of the DoME project.
Remove the print() method from class Item and move it into the Video and CD classes.
Compile. What do you observe?

 the item  class compiles. however the DVD class and CD class cannot access the superclass fields.
2
In your DoME project, add a print() method in class Item again. For now write the method body with a single statement that prints out only the title. Then modify the print() methods in CD andVideo so that the CD version prints out only the artist and the Video version prints only the director. This removes the other errors ecountered above.
You should now have a situation coressponding to figure 9.4 in the text, with print() methods in three classes. Compile your project. This design should work, if there are errors remove them.
Before executing, predict which of the print()methods will get called if you execute theDatabase list() method.
Try it out: Enter a CD and a video into the database and call the Database list() method. Which print() methods were executed?
Was your prediction correct?
Try to explain your observations.

    public void print()
    {
        System.out.print("title: " + title);
        
    } 

 public void print()
    {
        System.out.print("Director:" + director);
       
    }

public void print()
    {
        System.out.print("Artist:" + artist);
       
    }



The class compiles!

3
Modify your latest version of the DoME project to include the super call in the print() method.
Test it.
Does it behave as expected?
Do you see any problems with this solution?



 public void print()
    {
        super.print();
        System.out.print("Artist:" + artist);
it compiles and behaves same as before

4
Change the format of the output so that it prints the string "CD: " or Video: " (depending on the type of item) in front of the details.

public void print()
    {
        super.print();
System.out.println("CD:")
        System.out.print("Artist:" + artist);
5
Look up toString in the library documentation.
What are its parameters?
What is its return type?

 no parameters
it returns type string
6
.... You can easily try this out.
Create an object of class Video in your project, and then invoke the toString() method from theObject submenu in the object's popup menu.



OK
7
The version of print() shown in Code 9.1 produces the output shown in text figure 9.9.
Reorder the staements in the method in your version of the DoME project so that it prints the details as shown in text Figure 9.10.

 print method in CD:

public void print()
    {
        System.out.print("CD: " + artist + ":   ");
        super.print();
        System.out.println("tracks: "+ numberOfTracks);
    }


print method in Item:

System.out.print(title);
        if (gotIt) {
            System.out.println("*");
        }
        else {
            System.out.println("");
        }
        System.out.println(playingTime + " minutes");
        System.out.println(comment);
8
Having to use a superclass call in print() is somewhat restrictive in the ways we can format the output, because it is dependent on the way the superclass formats its fields.
Make any necessary changes to the Item class and to the print() method of CD so that it produces the output shown in text Figure 9.11.
Any changes you make to the Item class should be visible only to its subclasses.
Hint: You used to use protected fields to do this.

?????



12
Assume you see the following lines of code:
Device dev = new Printer();
dev.getName();
Printer is a subclass of Device. Which of these classes must have a definition of methodgetName() for this code to compile?

Device, since it is the superclass
13
In the same situation as in the previous exercise, if both classes have an implementation of methodgetName(), which one will be executed?
The method in class printer
14
Assume you write a class Student, which does not have a declared superclass. You do not write a toString() method.
Consider the following lines of code.
Student st = new Student();
String s = st.toString();
Will these lines compile?
What exactly will happen when you try to execute?

Student is a subclass of OBJECT, therefore the method will work since it is invoked from the object class.

15
In the same situation as the previous exercise (class Student, no toString() method), will the following lines compile?
Why?
Student st = new Student();
System.out.println(st);

Yes, it will return the toString output since it is in the Superduper class object.
16
Assume your class Student overrides toString()so that it returns the student's name. You now have a list of students. Will the following code compile?
If not, why not?
If yes, what will it print?
Explain in detail what happens.
Iterator it = myList.iterator();
while (it.hasNext())
{
        System.out.println(it.next());
}

?????
17
Write a few lines of code that result in a situation where a variable x has the static type T and thedynamic type D.
T x = new D;