480 likes | 563 Views
Further abstraction techniques. Abstract classes and interfaces. 1.0. Main concepts to be covered. Abstract classes Interfaces Multiple inheritance. Simulations. Programs regularly used to simulate real-world activities. city traffic the weather nuclear processes
E N D
Further abstraction techniques Abstract classes and interfaces 1.0
Main concepts to be covered • Abstract classes • Interfaces • Multiple inheritance Lecture 9: Abstraction Techniques
Simulations • Programs regularly used to simulate real-world activities. • city traffic • the weather • nuclear processes • stock market fluctuations • environmental changes • LAN networks • animal behavior Lecture 9: Abstraction Techniques
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. Lecture 9: Abstraction Techniques
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?’ Lecture 9: Abstraction Techniques
Predator-prey simulations • 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 ... Lecture 9: Abstraction Techniques
The foxes-and-rabbits project Lecture 9: Abstraction Techniques
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. Lecture 9: Abstraction Techniques
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. Lecture 9: Abstraction Techniques
Example of the visualization Lecture 9: Abstraction Techniques
A Rabbit’s state // 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(); Lecture 9: Abstraction Techniques
A Rabbit’s state // 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; Lecture 9: Abstraction Techniques
A Rabbit’s behavior • 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. Lecture 9: Abstraction Techniques
A Rabbit’s behavior 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); } Lecture 9: Abstraction Techniques
A Rabbit’s behavior 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; }}} Lecture 9: Abstraction Techniques
A Rabbit’s behavior 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; } Lecture 9: Abstraction Techniques
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. Lecture 9: Abstraction Techniques
A Fox’s state public class Fox { Static 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. } Lecture 9: Abstraction Techniques
A Fox’s behavior • Managed from the hunt method. • Foxes also age and breed. • They become hungry. • They hunt for food in adjacent locations. Lecture 9: Abstraction Techniques
A Fox’s behavior 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); } Lecture 9: Abstraction Techniques
A Fox’s behavior // Move towards the source of food if found. Location newLocation = findFood(currentField, location); if(newLocation == null) {// no food found–moverandomly 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; }}} Lecture 9: Abstraction Techniques
A Fox’s behavior 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; } Lecture 9: Abstraction Techniques
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? Lecture 9: Abstraction Techniques
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. Lecture 9: Abstraction Techniques
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(); Lecture 9: Abstraction Techniques
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(); } } Lecture 9: Abstraction Techniques
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 Lecture 9: Abstraction Techniques
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. Lecture 9: Abstraction Techniques
The Animal superclass • Place common fields in Animal: • age, alive, location • Method renaming to support information hiding: • run and hunt become act. • Simulator can now be significantly decoupled. Lecture 9: Abstraction Techniques
Revised (decoupled) iteration for(Iterator iter = animals.iterator(); iter.hasNext(); ) { Animal animal = (Animal)iter.next(); if(animal.isAlive()) { animal.act(field, updatedField, newAnimals); } else { iter.remove(); } } Lecture 9: Abstraction Techniques
The act method of Animal • Static type checking requires an act method in Animal. • There is no obvious shared implementation. • Define act as abstract:abstract public void act(Field currentField, Field updatedField, List newAnimals); Lecture 9: Abstraction Techniques
Abstract classes and methods • Abstract methods have abstract in the signature. • Abstract methods have no body. • Abstract methods make the class abstract. • Abstract classes cannot be instantiated. • Concrete subclasses complete the implementation. Lecture 9: Abstraction Techniques
The Animal class public abstract class Animal { fields omitted /** * Make this animal act - that is: make it do * whatever it wants/needs to do. */ abstract public void act(Field currentField, Field updatedField, List newAnimals); other methods omitted } Lecture 9: Abstraction Techniques
More abstract methods public boolean canBreed() { return age >= getbreedingAge() } abstract public int getBreedingAge(); • Note: fields are handled differently from methods in Java: they cannot be overridden by subclass version • both Rabbit and Fox have their own static field BREEDING_AGE and Animal has none. Lecture 9: Abstraction Techniques
Further abstraction Lecture 9: Abstraction Techniques
Selective drawing(multiple inheritance) // let all animals act for(Iterator iter = actors.iterator(); iter.hasNext();) { Actor actor = (Actor) iter.next(); actor.act(…); } for(Iterator iter = drawables.iterator(); iter.hasNext();) { Drawable item = (Drawable) iter.hasNext(); item.draw(…); } Lecture 9: Abstraction Techniques
Selective drawing(multiple inheritance) Lecture 9: Abstraction Techniques
Multiple inheritance • Having a class inherit directly from multiple ancestors. • Each language has its own rules. • How to resolve competing definitions? • Java forbids it for classes. • Java permits it for interfaces. • No competing implementation. Lecture 9: Abstraction Techniques
An Actor interface public interface Actor { /** * Perform the actor's daily behavior. * Transfer the actor to updatedField if it is * to participate in further steps of the simulation. * @param currentField The current state of the field. * @param location The actor's location in the field. * @param updatedField The updated state of the field. */ void act(Field currentField, Location location, Field updatedField); } Lecture 9: Abstraction Techniques
Interfaces • A Java interface is a specification of a type (in the form of a type name and methods) that does not define any implementation of methods • uses interface instead of class • all methods are public (no need to mention) • all methods are abstract (no need to mention) • no constructors • all constant fields are allowed (public static final) Lecture 9: Abstraction Techniques
Classes implement an interface public class Fox extends Animal implements Drawable { ... } public class Hunter implements Actor, Drawable { ... } Lecture 9: Abstraction Techniques
Interfaces as types • Implementing classes do not inherit code, but ... • ... implementing classes are subtypes of the interface type. • So, polymorphism is available with interfaces as well as classes. Lecture 9: Abstraction Techniques
Interfaces as specifications • Strong separation of functionality from implementation. • Though parameter and return types are mandated. • Clients interact independently of the implementation. • But clients can choose from alternative implementations. Lecture 9: Abstraction Techniques
Alternative implementations Lecture 9: Abstraction Techniques
Review • Inheritance can provide shared implementation. • Concrete and abstract classes. • Inheritance provides shared type information. • Classes and interfaces. Lecture 9: Abstraction Techniques
Review • Abstract methods allow static type checking without requiring implementation. • Abstract classes function as incomplete superclasses. • No instances. • Abstract classes support polymorphism. Lecture 9: Abstraction Techniques
Interfaces • Interfaces provide specification without implementation. • Interfaces are fully abstract. • Interfaces support polymorphism. • Java interfaces support multiple inheritance. Lecture 9: Abstraction Techniques
abstract class interfaces instanceof Concepts Lecture 9: Abstraction Techniques