Further abstraction techniques Further abstraction techniques Abstract classes and interfaces 1.0
Main concepts to be covered Main concepts to be covered � Abstract classes � Interfaces � Multiple inheritance 01/12/2005 Lecture 9: Abstraction Techniques 2
Simulations Simulations � Programs regularly used to simulate real-world activities. – city traffic – the weather – nuclear processes – stock market fluctuations – environmental changes – LAN networks – animal behavior 01/12/2005 Lecture 9: Abstraction Techniques 3
Simulations Simulations � They are often only partial simulations. � They often involve simplifications. – Greater detail has the potential to provide greater accuracy. – Greater detail typically requires more resources. � Processing power. � Simulation time. 01/12/2005 Lecture 9: Abstraction Techniques 4
Benefits of simulations Benefits of simulations � Support useful prediction. – The weather. � Allow experimentation. – Safer, cheaper, quicker. � Example: – ‘How will the wildlife be affected if we cut a highway through the middle of this national park?’ 01/12/2005 Lecture 9: Abstraction Techniques 5
Predator- -prey simulations prey simulations Predator � There is often a delicate balance between species. – A lot of prey means a lot of food. – A lot of food encourages higher predator numbers. – More predators eat more prey. – Less prey means less food. – Less food means ... 01/12/2005 Lecture 9: Abstraction Techniques 6
The foxes- -and and- -rabbits project rabbits project The foxes 01/12/2005 Lecture 9: Abstraction Techniques 7
Main classes of interest Main classes of interest � Fox – Simple model of a type of predator. � Rabbit – Simple model of a type of prey. � Simulator – Manages the overall simulation task. – Holds a collection of foxes and rabbits. 01/12/2005 Lecture 9: Abstraction Techniques 8
The remaining classes The remaining classes � Field – Represents a 2D field. � Location – Represents a 2D position. � SimulatorView , FieldStats , Counter – Maintain statistics and present a view of the field. 01/12/2005 Lecture 9: Abstraction Techniques 9
Example of the visualization Example of the visualization 01/12/2005 Lecture 9: Abstraction Techniques 10
A Rabbit’ ’s state s state A Rabbit // Characteristics shared by all rabbits (static fields). // The age at which a rabbit can start to breed. private static final int BREEDING_AGE = 5; // The age to which a rabbit can live. private static final int MAX_AGE = 50; // The likelihood of a rabbit breeding. private static final double BREEDING_PROBABILITY = 0.15; // The maximum number of births. private static final int MAX_LITTER_SIZE = 5; // A shared random number generator to control breeding. private static final Random rand = new Random(); 01/12/2005 Lecture 9: Abstraction Techniques 11
A Rabbit’ ’s state s state A Rabbit // Individual characteristics (instance fields). // The rabbit's age. private int age; // Whether the rabbit is alive or not. private boolean alive; // The rabbit's position private Location location; 01/12/2005 Lecture 9: Abstraction Techniques 12
A Rabbit’ ’s behavior s behavior A Rabbit � Managed from the run method. � Age incremented at each simulation ‘step’. – A rabbit could die at this point. � Rabbits that are old enough might breed at each step. – New rabbits could be born at this point. 01/12/2005 Lecture 9: Abstraction Techniques 13
A Rabbit’ ’s behavior s behavior A Rabbit public Rabbit(boolean randomAge){…} public void run(Field updatedField, List newRabbits) { incrementAge(); if(alive) { int births = breed(); for(int b = 0; b < births; b++) { Rabbit newRabbit = new Rabbit(false); newRabbits.add(newRabbit); Location loc = updatedField.randomAdjacentLocation(location); newRabbit.setLocation(loc); updatedField.place(newRabbit, loc); } 01/12/2005 Lecture 9: Abstraction Techniques 14
A Rabbit’ ’s behavior s behavior A Rabbit Location newLocation = updatedField.freeAdjacentLocation(location); // Only transfer to the updated field if //there was a free location if(newLocation != null) { setLocation(newLocation); updatedField.place(this, newLocation); } else { // can neither move nor stay – //overcrowding - all locations taken alive = false; }}} 01/12/2005 Lecture 9: Abstraction Techniques 15
A Rabbit’ ’s behavior s behavior A Rabbit private void incrementAge() { age++; if(age > MAX_AGE) { alive = false; } } private int breed() { int births = 0; if(canBreed() && rand.nextDouble() <= BREEDING_PROBABILITY) { births = rand.nextInt(MAX_LITTER_SIZE) + 1; } return births; } 01/12/2005 Lecture 9: Abstraction Techniques 16
Rabbit simplifications Rabbit simplifications � Rabbits do not have different genders. – In effect, all are female. � The same rabbit could breed at every step. � All rabbits die at the same age. 01/12/2005 Lecture 9: Abstraction Techniques 17
A Fox’ ’s state s state A Fox public class Fox { S tatic fields omitted // The fox's age. private int age; // Whether the fox is alive or not. private boolean alive; // The fox's position private Location location; // The fox's food level, which is increased // by eating rabbits. private int foodLevel; Methods omitted. } 01/12/2005 Lecture 9: Abstraction Techniques 18
A Fox’ ’s behavior s behavior A Fox � Managed from the hunt method. � Foxes also age and breed. � They become hungry. � They hunt for food in adjacent locations. 01/12/2005 Lecture 9: Abstraction Techniques 19
A Fox’ ’s behavior s behavior A Fox public void hunt(Field currentField, Field updatedField, List newFoxes) { incrementAge(); incrementHunger(); if(isAlive()) { // New foxes are born into adjacent locations. int births = breed(); for(int b = 0; b < births; b++) { Fox newFox = new Fox(false); newFoxes.add(newFox); Location loc = updatedField.randomAdjacentLocation(location); newFox.setLocation(loc); updatedField.place(newFox, loc); } 01/12/2005 Lecture 9: Abstraction Techniques 20
A Fox’ ’s behavior s behavior A Fox // Move towards the source of food if found. Location newLocation = findFood(currentField, location); if(newLocation == null) {// no food found –move randomly newLocation = updatedField.freeAdjacentLocation(location); } if(newLocation != null) { setLocation(newLocation); updatedField.place(this, newLocation); } else { // can neither move nor stay - overcrowding – all // locations taken alive = false; }}} 01/12/2005 Lecture 9: Abstraction Techniques 21
A Fox’ ’s behavior s behavior A Fox private Location findFood(Field field, Location location) { Iterator adjacentLocations = field.adjacentLocations(location); while(adjacentLocations.hasNext()) { Location where = (Location) adjacentLocations.next(); Object animal = field.getObjectAt(where); if(animal instanceof Rabbit) { Rabbit rabbit = (Rabbit) animal; if(rabbit.isAlive()) { rabbit.setEaten(); foodLevel = RABBIT_FOOD_VALUE; return where; }}} return null; } 01/12/2005 Lecture 9: Abstraction Techniques 22
Configuration of foxes Configuration of foxes � Similar simplifications to rabbits. � Hunting and eating could be modeled in many different ways. – Should food level be additive? – Is a hungry fox more or less likely to hunt? � Are simplifications ever acceptable? 01/12/2005 Lecture 9: Abstraction Techniques 23
The Simulator class The Simulator class � Three key components: – Setup in the constructor. – The populate method. � Each animal is given a random starting age. – The simulateOneStep method. � Iterates over the population. � Two Field objects are used: field and updatedField . 01/12/2005 Lecture 9: Abstraction Techniques 24
The update step The update step public class Simulator { … public void simulateOneStep() { step++; newAnimals.clear(); // let all animals act for(Iterator iter = animals.iterator(); iter.hasNext(); ) { Object animal = iter.next(); 01/12/2005 Lecture 9: Abstraction Techniques 25
The update step The update step if(animal instanceof Rabbit) { Rabbit rabbit = (Rabbit)animal; if(rabbit.isAlive()) { rabbit.run(updatedField, newAnimals); } else { iter.remove(); } } else if(animal instanceof Fox) { Fox fox = (Fox)animal; if(fox.isAlive()) { fox.hunt(field, updatedField, newAnimals); } else { iter.remove(); } } 01/12/2005 Lecture 9: Abstraction Techniques 26
Instanceof Instanceof � Checking an object’s dynamic type – obj instanceof Myclass � General not considered good practice � Make code to depend on the exact type of objects. � The usage of instanceof is an indicator of refactoring 01/12/2005 Lecture 9: Abstraction Techniques 27
Room for improvement Room for improvement � Fox and Rabbit have strong similarities but do not have a common superclass. � The Simulator is tightly coupled to the specific classes. – It ‘knows’ a lot about the behavior of foxes and rabbits. 01/12/2005 Lecture 9: Abstraction Techniques 28
Recommend
More recommend