1 / 48

Further abstraction techniques

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

vahe
Download Presentation

Further abstraction techniques

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Further abstraction techniques Abstract classes and interfaces 1.0

  2. Main concepts to be covered • Abstract classes • Interfaces • Multiple inheritance Lecture 9: Abstraction Techniques

  3. 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

  4. 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

  5. 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

  6. 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

  7. The foxes-and-rabbits project Lecture 9: Abstraction Techniques

  8. 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

  9. 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

  10. Example of the visualization Lecture 9: Abstraction Techniques

  11. 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

  12. 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

  13. 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

  14. 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

  15. 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

  16. 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

  17. 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

  18. 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

  19. 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

  20. 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

  21. 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

  22. 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

  23. 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

  24. 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

  25. 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

  26. 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

  27. 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

  28. 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

  29. 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

  30. 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

  31. 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

  32. 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

  33. 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

  34. 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

  35. Further abstraction Lecture 9: Abstraction Techniques

  36. 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

  37. Selective drawing(multiple inheritance) Lecture 9: Abstraction Techniques

  38. 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

  39. 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

  40. 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

  41. Classes implement an interface public class Fox extends Animal implements Drawable { ... } public class Hunter implements Actor, Drawable { ... } Lecture 9: Abstraction Techniques

  42. 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

  43. 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

  44. Alternative implementations Lecture 9: Abstraction Techniques

  45. Review • Inheritance can provide shared implementation. • Concrete and abstract classes. • Inheritance provides shared type information. • Classes and interfaces. Lecture 9: Abstraction Techniques

  46. 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

  47. Interfaces • Interfaces provide specification without implementation. • Interfaces are fully abstract. • Interfaces support polymorphism. • Java interfaces support multiple inheritance. Lecture 9: Abstraction Techniques

  48. abstract class interfaces instanceof Concepts Lecture 9: Abstraction Techniques

More Related