Sunday, 28 November 2010

Chapter 10 FINALLY YES!

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?

 Done. The number changes. The method simulateOneStep() allows the number and position to change. 
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?

 Done. Yes the number of foxes always change. That is due to the simulateOneStep() method. The system we are working in represents the ecosystem and it consists of two species, the foxes and the rabbits. The foxes need to be fed to survive and also need to multiply by mating, while the rabbits are being fed on.
3
Call the simulate() method to run the simulation continuously for a significant number of steps, such as 50 or 100.
Do the numbers of foxes and rabbits increase of decrease at similar rates?

 If we take this situation in math terms, and the population of the rabbits and foxes can be described as functions, they both are inverses of each other. This is because, when the foxes population go up, the rabbits must go down, because foxes survive on rabbits and if foxes goes down, then eventually rabbits go up, or it could also be that insufficient number of rabbits led to starvation.     
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.

 The situation is fluctuating, but there are sometimes when it reaches extreme, that is when all rabbits perish, or all foxes die.  The population of both the foxes and rabbits are small at the start which is the only part which is not periodic. After this things change. 
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?

 Done. There is a general flow through the entire simulation. This is what we can call phases. 
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?

At some points, all rabbits die or the foxes die. This situation is very rare, but it happens sometimes. When rabbit population is small compared to foxes, rabbits die and when foxes are small, then foxes due, but when both the population are equally small, foxes die. 

Do you feel that omitting gender as an attribute in the Rabbit class is likely to lead to an inaccurate simulation?
 Yes. It is a very unrealistic situation here because one rabbit can multiply by itself which is not possible in real life.So to make it more real, we have to assign genders to all the rabbits, or a gender.method in the rabbit class. But in such a simulation, I dont think the sex of the species matter because looking over a long period of time, gender wont matter, cos species will grow, and decline but that is the rule of the ecosystem. Adding the gender wont help, because then we have to give specific attributes to every little thing in the simulation, as in which kind of rabbits mate more, maybe rabbits will have different species of their own, and stuff. This simulation is general and effective to learn from.
8
Are there other simplifications that you feel are present in our implementation of the Rabbit class, compared with real life?
Do you feel that these could have a significant impact on the accuracy of the simulation?

 Nope. I dont see any plus, this is a good representation of the ecosystem, maybe if we wanted to get a bit more specific, we could add the feature of mating season, or weather conditions, when rabbits hibernate or migrate. 
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?

 Done. If the breeding probability of the rabbits is lower only two things can happen, either they extinct themselves by not being able to mate, or they get eaten up quickly by foxes and foxes die eventually. If it is high, then the population of the foxes will also increase. 
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.
 We can be creative here now. We could add something like how many months a rabbit should be alive, so that it is consumable by the foxes. Or maybe, after 1 female rabbit is eaten, 2 male rabbit must be eaten or something like that.  
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?
 It we increase too much, rabbits will be eaten up quickly, and if we decrease it, a lot more foxes will be alive but less can eat the rabbits. 
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?

 If we put extreme figures, one species will die faster then the other. The default ones are the most stable ones. 
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, the size of the field is very essential. If we make it too big, then the foxes will be too far from the rabbits and wont be able to search for food and will die. 
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.

 Done. This results in the rabbits being consumed quickly and eventually this leads to starvation of the foxes which die soon after. 
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.

Hunger level will increase and at one point, when the rabbits all die, foxes will die quickly too. If we do not put a hunger level, then it wont increase, and foxes will be able to live longer even after rabbits die. 
16
Modify the populate() method of Simulatorto determine whether not setting an initail random age for foxes and rabbits is catastophic.
 Yes this is hazardous, because by default all the foxes at any given age can consume rabbits, but the rabbits need to attain a certain age before they can reproduce. This is unhealthy and leads to killing all the rabbits quickly followed by the foxes dieing quickly after. 
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?

If it goes into the cycle, then it is like a normal simulation. 
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?

It will reduce the number of foxes in the world. But it could also result in increase of the foxes since there are more rabbits to feed on. 
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, it is possible to happen but such a change in not necessary as we can learn effectively from the simulation at hand at the moment.  


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.

 They all share the following fields and methods:
max_age
breeding_probability 
age
location
breed()
canBreed()
setLocation()
Some are class specific. 
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.

These are similar methods in all the classes. 
incrementAge()
canBreed()
isAlive()
setLocation()
breed()
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?

 Some of the methods use variables and we need to change these variables so that it is different for the rabbits and the fox class.But by creating a superclass and adding, Breeding_Age as a method, we can use it and manipulate it and over rule it in the subclasses.
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?

 Done. 
24
Create the Animal superclass in your version of the project. Make the changes discussed in the text. Ensure that the simulation works in a similar manner as before.
 Done. I created a superclass because during run time it executes it the methods. 
25
How has using inheritance improved the project so far?
Discuss.

 Less coding, so therefore it takes less memory. It is much easier to modify coding with a superclass.
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?
The variable inside the loop Animal type so it makes it a method of the Animal class. And the object class does not have an act() method.
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.
 II am not sure about ABSTRACT class. I will ask in class. 
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.
Done.You cant make objects of abstract class. When a method is abstract, the whole class must be abstract.Abstract classes were made especially for inheritance. 
29
Could it ever make sense to define a class as abstract if it has no abstract methods? Discuss this.
 Yes. Making a class, that extends to other classes, for inheritance that makes the class abstract. 
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?
 The benefit would be, again, less code. But more importantly, it would make it clearer for the reader to understand and it would just be smarter and better design.
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?
 We need to know inheritance to make minor changes in large amounts of coding. 
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.
 Making a superclass, helps us change coding by just changing one code for all the classes in the simulation. 
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?
 The canBreed() method uses constants (final fields) that are declared in the Fox and Rabbit classes. Moving those fields up to the Animal class would be disastrous since the numbers that those fields were assigned are specific to the Rabbit and Fox classes and cannot be the same. That is, unless you use the trick that I have suggested.
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.
The book tricks are simple and easy to execute.
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.
 Done.We have to make sure that getBreedingAge() and getMaxAge(), these methods are abstract. They have to be override the subclass methods. 
38
Can the breed() method be moved to Animal?

If so, make this change.
 Done. This method can be moved to the animal class. But we have to replace methods over fields.
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.
 Done. We have the make sure that the methods in the subclasses are visible so they do not get over ridden.
40
Was is possible to make these changes without having any impact 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?
 Done. 
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.
 Done. I had to create a new class of Lion which would fight with the fox for the rabbits. It was easy, just had to copy the coding from the fox.
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?
 Done. We have to make the animal class a subclass of the Actor class and had to copy some methods into the actor class. But the actor class is abstract, just like the animal class.
43
Redefine the abstract class Actor in your project as an interface.

Does the simulation still compile?

Does it run?
 Done. The actor class works fine, but I am not sure how to describe this, it works like an interface if I am not wrong. 
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?
Public static final. If we do not define which methods are visible, then they become public static final, or else they will show a compilation error. 
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;
}
...
}
 The field cannot be private
Interfaces do not have constructors
 They wont implement. 
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?
 Done. The hunter shoots himself and dies. We just make the same methods as the actor class, and compile it. 
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?
  getLast(), removeRange(), and trimToSize() getFirst(), are the methods which appear in the arraylist and the linkedlist. 
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?
 Comparator and list are both parameters.   They execute the List interface but both need two parameters, one implementing the List interface, while the other deals with couple interface. 
49
Investigate the Comparator interface.
Define a simple class that implements Comparator.
Create a collection containing objects of this class and sort the collection.
 Done. Still a bit confused about the comparator interface though. I will do future research in class. 
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.
 Done. Interfaces are very essential. They make the system run more smoothly and more flexible to make changes. 
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).
 Done. We have to change the placement of the code.
52
Can you manage to have both views active at the same time?
 Yes. We need to add this in the simulator class. 
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
     Yes we can do it when we don't want to create an object for a certain class. 
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?)
 G and X  must both be extended to U so either G and X can be both interface or both can be. X extends to B and Z extends to U.
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.


Abstract staff - teaching, support, tutors
interface techincal- teachstaff, studentTech

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?
 Done. here it removes the actor from the simulation, instead of deleting the whole object but it still remains in the memory. This made the process a bit slow.
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?
 It is always better to use interfaces as substitutes to abstract classes. In printjobadapter, not all methods are abstract. I can choose which methods I want to use in the PrintJobListener. 

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.
Done. Person class has to implement the comparable interface. The class has to use methods from the comparable interface. The person object have to be organized according to the age, there for we have to use the comparable methods.