Further abstraction techniques Further abstraction techniques - - PowerPoint PPT Presentation

further abstraction techniques further abstraction
SMART_READER_LITE
LIVE PREVIEW

Further abstraction techniques Further abstraction techniques - - PowerPoint PPT Presentation

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:


slide-1
SLIDE 1

Further abstraction techniques Further abstraction techniques

Abstract classes and interfaces

1.0

slide-2
SLIDE 2

01/12/2005 Lecture 9: Abstraction Techniques 2

Main concepts to be covered Main concepts to be covered

Abstract classes Interfaces Multiple inheritance

slide-3
SLIDE 3

01/12/2005 Lecture 9: Abstraction Techniques 3

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

slide-4
SLIDE 4

01/12/2005 Lecture 9: Abstraction Techniques 4

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.

slide-5
SLIDE 5

01/12/2005 Lecture 9: Abstraction Techniques 5

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?’

slide-6
SLIDE 6

01/12/2005 Lecture 9: Abstraction Techniques 6

Predator Predator-

  • prey simulations

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

slide-7
SLIDE 7

01/12/2005 Lecture 9: Abstraction Techniques 7

The foxes The foxes-

  • and

and-

  • rabbits project

rabbits project

slide-8
SLIDE 8

01/12/2005 Lecture 9: Abstraction Techniques 8

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.

slide-9
SLIDE 9

01/12/2005 Lecture 9: Abstraction Techniques 9

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

  • f the field.
slide-10
SLIDE 10

01/12/2005 Lecture 9: Abstraction Techniques 10

Example of the visualization Example of the visualization

slide-11
SLIDE 11

01/12/2005 Lecture 9: Abstraction Techniques 11

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

slide-12
SLIDE 12

01/12/2005 Lecture 9: Abstraction Techniques 12

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

slide-13
SLIDE 13

01/12/2005 Lecture 9: Abstraction Techniques 13

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

slide-14
SLIDE 14

01/12/2005 Lecture 9: Abstraction Techniques 14

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

slide-15
SLIDE 15

01/12/2005 Lecture 9: Abstraction Techniques 15

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

slide-16
SLIDE 16

01/12/2005 Lecture 9: Abstraction Techniques 16

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

slide-17
SLIDE 17

01/12/2005 Lecture 9: Abstraction Techniques 17

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.

slide-18
SLIDE 18

01/12/2005 Lecture 9: Abstraction Techniques 18

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

slide-19
SLIDE 19

01/12/2005 Lecture 9: Abstraction Techniques 19

A Fox A Fox’ ’s behavior s behavior

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

slide-20
SLIDE 20

01/12/2005 Lecture 9: Abstraction Techniques 20

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

slide-21
SLIDE 21

01/12/2005 Lecture 9: Abstraction Techniques 21

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

slide-22
SLIDE 22

01/12/2005 Lecture 9: Abstraction Techniques 22

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

slide-23
SLIDE 23

01/12/2005 Lecture 9: Abstraction Techniques 23

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?

slide-24
SLIDE 24

01/12/2005 Lecture 9: Abstraction Techniques 24

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.

slide-25
SLIDE 25

01/12/2005 Lecture 9: Abstraction Techniques 25

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();

slide-26
SLIDE 26

01/12/2005 Lecture 9: Abstraction Techniques 26

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

slide-27
SLIDE 27

01/12/2005 Lecture 9: Abstraction Techniques 27

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

  • bjects.

The usage of instanceof is an indicator of refactoring

slide-28
SLIDE 28

01/12/2005 Lecture 9: Abstraction Techniques 28

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.

slide-29
SLIDE 29

01/12/2005 Lecture 9: Abstraction Techniques 29

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

slide-30
SLIDE 30

01/12/2005 Lecture 9: Abstraction Techniques 30

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

slide-31
SLIDE 31

01/12/2005 Lecture 9: Abstraction Techniques 31

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

slide-32
SLIDE 32

01/12/2005 Lecture 9: Abstraction Techniques 32

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

slide-33
SLIDE 33

01/12/2005 Lecture 9: Abstraction Techniques 33

The Animal class 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);

  • ther methods omitted

}

slide-34
SLIDE 34

01/12/2005 Lecture 9: Abstraction Techniques 34

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

slide-35
SLIDE 35

01/12/2005 Lecture 9: Abstraction Techniques 35

Further abstraction Further abstraction

slide-36
SLIDE 36

01/12/2005 Lecture 9: Abstraction Techniques 36

Selective drawing Selective drawing (multiple inheritance) (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(…); }

slide-37
SLIDE 37

01/12/2005 Lecture 9: Abstraction Techniques 37

Selective drawing Selective drawing (multiple inheritance) (multiple inheritance)

slide-38
SLIDE 38

01/12/2005 Lecture 9: Abstraction Techniques 38

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

slide-39
SLIDE 39

01/12/2005 Lecture 9: Abstraction Techniques 39

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

slide-40
SLIDE 40

01/12/2005 Lecture 9: Abstraction Techniques 40

Interfaces 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)

slide-41
SLIDE 41

01/12/2005 Lecture 9: Abstraction Techniques 41

Classes implement an Classes implement an interface interface

public class Fox extends Animal implements Drawable { ... } public class Hunter implements Actor, Drawable { ... }

slide-42
SLIDE 42

01/12/2005 Lecture 9: Abstraction Techniques 42

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

slide-43
SLIDE 43

01/12/2005 Lecture 9: Abstraction Techniques 43

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

slide-44
SLIDE 44

01/12/2005 Lecture 9: Abstraction Techniques 44

Alternative implementations Alternative implementations

slide-45
SLIDE 45

01/12/2005 Lecture 9: Abstraction Techniques 45

Review Review

Inheritance can provide shared implementation.

– Concrete and abstract classes.

Inheritance provides shared type information.

– Classes and interfaces.

slide-46
SLIDE 46

01/12/2005 Lecture 9: Abstraction Techniques 46

Review Review

Abstract methods allow static type checking without requiring implementation. Abstract classes function as incomplete superclasses.

– No instances.

Abstract classes support polymorphism.

slide-47
SLIDE 47

01/12/2005 Lecture 9: Abstraction Techniques 47

Interfaces Interfaces

Interfaces provide specification without implementation.

– Interfaces are fully abstract.

Interfaces support polymorphism. Java interfaces support multiple inheritance.

slide-48
SLIDE 48

01/12/2005 Lecture 9: Abstraction Techniques 48

Concepts Concepts

abstract class interfaces instanceof