48
Further abstraction Further abstraction techniques techniques Abstract classes and interfaces 1.0

Further abstraction techniques Abstract classes and interfaces 1.0

  • View
    217

  • Download
    1

Embed Size (px)

Citation preview

Further abstraction techniquesFurther abstraction techniques

Abstract classes and interfaces

1.0

09/12/2004 Lecture 9: Abstraction Techniques 2

Main concepts to be coveredMain concepts to be covered

Abstract classesInterfacesMultiple inheritance

09/12/2004 Lecture 9: Abstraction Techniques 3

SimulationsSimulations

Programs regularly used to simulate real-world activities.– city traffic– the weather– nuclear processes– stock market fluctuations– environmental changes– LAN networks– animal behavior

09/12/2004 Lecture 9: Abstraction Techniques 4

SimulationsSimulations

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.

09/12/2004 Lecture 9: Abstraction Techniques 5

Benefits of simulationsBenefits 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?’

09/12/2004 Lecture 9: Abstraction Techniques 6

Predator-prey simulationsPredator-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 ...

09/12/2004 Lecture 9: Abstraction Techniques 7

The foxes-and-rabbits projectThe foxes-and-rabbits project

09/12/2004 Lecture 9: Abstraction Techniques 8

Main classes of interestMain 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.

09/12/2004 Lecture 9: Abstraction Techniques 9

The remaining classesThe remaining classes

Field– Represents a 2D field.

Location– Represents a 2D position.

SimulatorView, FieldStats, Counter– Maintain statistics and present a view

of the field.

09/12/2004 Lecture 9: Abstraction Techniques 10

Example of the visualizationExample of the visualization

09/12/2004 Lecture 9: Abstraction Techniques 11

A Rabbit’s stateA 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();

09/12/2004 Lecture 9: Abstraction Techniques 12

A Rabbit’s stateA 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;

09/12/2004 Lecture 9: Abstraction Techniques 13

A Rabbit’s behaviorA 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.

09/12/2004 Lecture 9: Abstraction Techniques 14

A Rabbit’s behaviorA 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); }

09/12/2004 Lecture 9: Abstraction Techniques 15

A Rabbit’s behaviorA 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; }}}

09/12/2004 Lecture 9: Abstraction Techniques 16

A Rabbit’s behaviorA 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; }

09/12/2004 Lecture 9: Abstraction Techniques 17

Rabbit simplificationsRabbit 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.

09/12/2004 Lecture 9: Abstraction Techniques 18

A Fox’s stateA Fox’s statepublic 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.}

09/12/2004 Lecture 9: Abstraction Techniques 19

A Fox’s behaviorA Fox’s behavior

Managed from the hunt method.Foxes also age and breed.They become hungry.They hunt for food in adjacent locations.

09/12/2004 Lecture 9: Abstraction Techniques 20

A Fox’s behaviorA 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); }

09/12/2004 Lecture 9: Abstraction Techniques 21

A Fox’s behaviorA Fox’s behavior

// 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; }}}

09/12/2004 Lecture 9: Abstraction Techniques 22

A Fox’s behaviorA Fox’s behaviorprivate 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; }

09/12/2004 Lecture 9: Abstraction Techniques 23

Configuration of foxesConfiguration 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?

09/12/2004 Lecture 9: Abstraction Techniques 24

The Simulator classThe 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.

09/12/2004 Lecture 9: Abstraction Techniques 25

The update stepThe 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();

09/12/2004 Lecture 9: Abstraction Techniques 26

The update stepThe update stepif(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(); }}

09/12/2004 Lecture 9: Abstraction Techniques 27

InstanceofInstanceof

Checking an object’s dynamic type– obj instanceof Myclass

General not considered good practiceMake code to depend on the exact type of

objects. The usage of instanceof is an indicator of

refactoring

09/12/2004 Lecture 9: Abstraction Techniques 28

Room for improvementRoom 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.

09/12/2004 Lecture 9: Abstraction Techniques 29

The Animal superclassThe 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.

09/12/2004 Lecture 9: Abstraction Techniques 30

Revised (decoupled) iterationRevised (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(); }}

09/12/2004 Lecture 9: Abstraction Techniques 31

The act method of AnimalThe 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);

09/12/2004 Lecture 9: Abstraction Techniques 32

Abstract classes and methodsAbstract 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.

09/12/2004 Lecture 9: Abstraction Techniques 33

The Animal classThe Animal classpublic 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}

09/12/2004 Lecture 9: Abstraction Techniques 34

More abstract methodsMore 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.

09/12/2004 Lecture 9: Abstraction Techniques 35

Further abstractionFurther abstraction

09/12/2004 Lecture 9: Abstraction Techniques 36

Selective drawingSelective drawing(multiple inheritance)(multiple inheritance)

// let all animals actfor(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(…);

}

09/12/2004 Lecture 9: Abstraction Techniques 37

Selective drawingSelective drawing(multiple inheritance)(multiple inheritance)

09/12/2004 Lecture 9: Abstraction Techniques 38

Multiple inheritanceMultiple 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.

09/12/2004 Lecture 9: Abstraction Techniques 39

An Actor interfaceAn 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);}

09/12/2004 Lecture 9: Abstraction Techniques 40

InterfacesInterfaces

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)

09/12/2004 Lecture 9: Abstraction Techniques 41

Classes implement an Classes implement an interfaceinterface

public class Fox extends Animal implements Drawable{ ...}

public class Hunter implements Actor, Drawable{ ...}

09/12/2004 Lecture 9: Abstraction Techniques 42

Interfaces as typesInterfaces 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.

09/12/2004 Lecture 9: Abstraction Techniques 43

Interfaces as specificationsInterfaces 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.

09/12/2004 Lecture 9: Abstraction Techniques 44

Alternative implementationsAlternative implementations

09/12/2004 Lecture 9: Abstraction Techniques 45

ReviewReview

Inheritance can provide shared implementation.– Concrete and abstract classes.

Inheritance provides shared type information.– Classes and interfaces.

09/12/2004 Lecture 9: Abstraction Techniques 46

ReviewReview

Abstract methods allow static type checking without requiring implementation.

Abstract classes function as incomplete superclasses.– No instances.

Abstract classes support polymorphism.

09/12/2004 Lecture 9: Abstraction Techniques 47

InterfacesInterfaces

Interfaces provide specification without implementation.– Interfaces are fully abstract.

Interfaces support polymorphism.Java interfaces support multiple inheritance.

09/12/2004 Lecture 9: Abstraction Techniques 48

ConceptsConcepts

abstract class interfaces

instanceof