Further abstraction techniques Abstract classes and interfaces 2.0 - - PowerPoint PPT Presentation

further abstraction techniques
SMART_READER_LITE
LIVE PREVIEW

Further abstraction techniques Abstract classes and interfaces 2.0 - - PowerPoint PPT Presentation

Objects First With Java A Practical Introduction Using BlueJ Further abstraction techniques Abstract classes and interfaces 2.0 Main concepts to be covered Abstract classes Interfaces Multiple inheritance Idea: Enhance class


slide-1
SLIDE 1

Objects First With Java A Practical Introduction Using BlueJ

Further abstraction techniques

Abstract classes and interfaces

2.0

slide-2
SLIDE 2

Objects First with Java - A Practical Introduction using BlueJ, David J. Barnes, Michael Kölling; extensions by HJB&TN for TUM-CSE, winter 2010/2011

2

Main concepts to be covered

  • Abstract classes
  • Interfaces
  • Multiple inheritance

Idea:

  • Enhance class structures
  • Improve maintainability & extendibility
slide-3
SLIDE 3

Objects First with Java - A Practical Introduction using BlueJ, David J. Barnes, Michael Kölling; extensions by HJB&TN for TUM-CSE, winter 2010/2011

3

Simulations – nothing strange for CSE people ☺

  • Programs often used to simulate real-

world activities or phenomena:

– traffic (rail, vehicle, pedestrian, …) – weather and climate – nuclear processes – stock market fluctuations – population predictions – …

slide-4
SLIDE 4

Objects First with Java - A Practical Introduction using BlueJ, David J. Barnes, Michael Kölling; extensions by HJB&TN for TUM-CSE, winter 2010/2011

4

Simulations

  • They are typically only partial simulations –

tackling and revealing part of the story

  • nly.
  • They usually involve simplifications

(models).

– Greater detail has the potential to provide greater accuracy. – Greater detail typically requires more resources:

  • Processing power.
  • Memory.
  • Simulation time.
slide-5
SLIDE 5

Objects First with Java - A Practical Introduction using BlueJ, David J. Barnes, Michael Kölling; extensions by HJB&TN for TUM-CSE, winter 2010/2011

5

Benefits of simulations – who is still to be convinced???

  • Understand – optimize – predict.
  • 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

Objects First with Java - A Practical Introduction using BlueJ, David J. Barnes, Michael Kölling; extensions by HJB&TN for TUM-CSE, winter 2010/2011

6

Predator-prey simulations

  • A standard scenario in population

dynamics.

  • 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

Objects First with Java - A Practical Introduction using BlueJ, David J. Barnes, Michael Kölling; extensions by HJB&TN for TUM-CSE, winter 2010/2011

7

The foxes-and-rabbits project

slide-8
SLIDE 8

Objects First with Java - A Practical Introduction using BlueJ, David J. Barnes, Michael Kölling; extensions by HJB&TN for TUM-CSE, winter 2010/2011

8

Main classes of interest

  • Fox

– Simple model of a type of predator.

  • Rabbit

– Simple model of a type of prey.

  • Simulator

– Creates the simulation’s initial state. – Manages the overall simulation task (i.e. performs a sequence of simulation steps where each animal is allowed to move). – Holds a collection of foxes and rabbits. – The “main program” in an imperative language.

slide-9
SLIDE 9

Objects First with Java - A Practical Introduction using BlueJ, David J. Barnes, Michael Kölling; extensions by HJB&TN for TUM-CSE, winter 2010/2011

9

The remaining classes

  • Field

– Represents a 2D enclosed field with positions arranged in matrix-type.

  • Location

– Represents a 2D position and can hold

  • ne animal at most.
  • SimulatorView, FieldStats, Counter

– Maintain statistics and present a view of the field – nothing to do with the model!

slide-10
SLIDE 10

Objects First with Java - A Practical Introduction using BlueJ, David J. Barnes, Michael Kölling; extensions by HJB&TN for TUM-CSE, winter 2010/2011

10

Example of the visualization

slide-11
SLIDE 11

Objects First with Java - A Practical Introduction using BlueJ, David J. Barnes, Michael Kölling; extensions by HJB&TN for TUM-CSE, winter 2010/2011

11

A Rabbit’s state

public class Rabbit { Static fields omitted. // 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; Methods omitted. }

Properties valid for all rabbits: Breeding age, maximum age, breeding probability, max. litter size, …

slide-12
SLIDE 12

Objects First with Java - A Practical Introduction using BlueJ, David J. Barnes, Michael Kölling; extensions by HJB&TN for TUM-CSE, winter 2010/2011

12

A Rabbit’s behaviour

  • Managed from the run method.
  • Movement executed and 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.

  • Random components: direction, breed

yes/no.

slide-13
SLIDE 13

Objects First with Java - A Practical Introduction using BlueJ, David J. Barnes, Michael Kölling; extensions by HJB&TN for TUM-CSE, winter 2010/2011

13

Rabbit simplifications

  • Rabbits do not have different

genders.

– In effect, all are female (which makes breeding really interesting …).

  • The same rabbit could breed at every

step (they are hard workers …).

  • All rabbits die at the same age.
  • Others?
slide-14
SLIDE 14

Objects First with Java - A Practical Introduction using BlueJ, David J. Barnes, Michael Kölling; extensions by HJB&TN for TUM-CSE, winter 2010/2011

14

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

A lot of similarity!

slide-15
SLIDE 15

Objects First with Java - A Practical Introduction using BlueJ, David J. Barnes, Michael Kölling; extensions by HJB&TN for TUM-CSE, winter 2010/2011

15

A Fox’s behaviour

  • Managed from the hunt method.
  • Foxes also age and breed.
  • They get hungry.
  • Hence, they hunt for food in adjacent

locations.

  • If a fox finds a rabbit in an adjacent

location, the rabbit is killed, and the fox’s food level is increased.

slide-16
SLIDE 16

Objects First with Java - A Practical Introduction using BlueJ, David J. Barnes, Michael Kölling; extensions by HJB&TN for TUM-CSE, winter 2010/2011

16

Configuration of foxes

  • Similar simplifications to rabbits.
  • Hunting and eating could be modelled

in many different ways.

– Should food level be additive? – Is a hungry fox more or less likely to hunt?

  • Are simplifications ever acceptable?
slide-17
SLIDE 17

Objects First with Java - A Practical Introduction using BlueJ, David J. Barnes, Michael Kölling; extensions by HJB&TN for TUM-CSE, winter 2010/2011

17

The Simulator class

  • Three key components:

– Setup of the simulation 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-18
SLIDE 18

Objects First with Java - A Practical Introduction using BlueJ, David J. Barnes, Michael Kölling; extensions by HJB&TN for TUM-CSE, winter 2010/2011

18

The update step – core of simulateOneStep

if(animal instanceof Rabbit) { Rabbit rabbit = (Rabbit)animal; rabbit.run(updatedField, newAnimals); } else if(animal instanceof Fox) { Fox fox = (Fox)animal; fox.hunt(field, updatedField, newAnimals); }

Missing: check whether the animal is still alive – and removing it if not! instanceof: checks whether a given object is an instance of a given class

slide-19
SLIDE 19

Objects First with Java - A Practical Introduction using BlueJ, David J. Barnes, Michael Kölling; extensions by HJB&TN for TUM-CSE, winter 2010/2011

19

Room for improvement (revisited, to some extent)

  • Fox and Rabbit have strong

similarities but do not have a common superclass.

  • The Simulator is tightly coupled to

specific classes.

– It ‘knows’ a lot about the behaviour of foxes and rabbits.

slide-20
SLIDE 20

Objects First with Java - A Practical Introduction using BlueJ, David J. Barnes, Michael Kölling; extensions by HJB&TN for TUM-CSE, winter 2010/2011

20

The Animal superclass

  • Place common fields in Animal:

– age, alive, location

  • Method renaming (polymorphic

method calls) to support information hiding:

– run and hunt become act.

  • Simulator can now be significantly

decoupled (neither rabbits nor foxes, just animals!).

slide-21
SLIDE 21

Objects First with Java - A Practical Introduction using BlueJ, David J. Barnes, Michael Kölling; extensions by HJB&TN for TUM-CSE, winter 2010/2011

21

Revised (decoupled) iteration

for(Iterator iter = animals.iterator(); iter.hasNext(); ) { Animal animal = (Animal)iter.next(); animal.act(field, updatedField, newAnimals); }

slide-22
SLIDE 22

Objects First with Java - A Practical Introduction using BlueJ, David J. Barnes, Michael Kölling; extensions by HJB&TN for TUM-CSE, winter 2010/2011

22

The act method of Animal

  • Static type checking requires an act

method in Animal- although it will never be executed!

  • There is no obvious shared implementation

– either run or hunt shall be executed, and nothing else.

  • Define act as abstract:

abstract public void act(Field currentField, Field updatedField, List newAnimals);

slide-23
SLIDE 23

Objects First with Java - A Practical Introduction using BlueJ, David J. Barnes, Michael Kölling; extensions by HJB&TN for TUM-CSE, winter 2010/2011

23

Abstract classes and methods

  • Abstract methods

– have abstract in the signature; – have no body; – make the class abstract.

  • Abstract classes

– cannot be instantiated; – are the only classes with abstract methods.

  • Concrete subclasses complete the implementation

(i.e. must provide implementations for all inherited abstract methods).

slide-24
SLIDE 24

Objects First with Java - A Practical Introduction using BlueJ, David J. Barnes, Michael Kölling; extensions by HJB&TN for TUM-CSE, winter 2010/2011

24

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

Objects First with Java - A Practical Introduction using BlueJ, David J. Barnes, Michael Kölling; extensions by HJB&TN for TUM-CSE, winter 2010/2011

25

Further abstraction

actor superclass – now, any simulation participant is considered to be an actor abstract!

slide-26
SLIDE 26

Objects First with Java - A Practical Introduction using BlueJ, David J. Barnes, Michael Kölling; extensions by HJB&TN for TUM-CSE, winter 2010/2011

26

Selective drawing (multiple inheritance)

  • Idea: separate the visualization from

the simulation.

  • Not everything existing/simulated

shall be drawn on the screen.

  • Hence, we may need a second

superclass!

slide-27
SLIDE 27

Objects First with Java - A Practical Introduction using BlueJ, David J. Barnes, Michael Kölling; extensions by HJB&TN for TUM-CSE, winter 2010/2011

27

Selective drawing (multiple inheritance)

slide-28
SLIDE 28

Objects First with Java - A Practical Introduction using BlueJ, David J. Barnes, Michael Kölling; extensions by HJB&TN for TUM-CSE, winter 2010/2011

28

Multiple inheritance

  • Having a class inherit directly from multiple

ancestors.

  • Then, the subclass has all the features of

all superclasses, and those defined in the subclass itself!

  • 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-29
SLIDE 29

Objects First with Java - A Practical Introduction using BlueJ, David J. Barnes, Michael Kölling; extensions by HJB&TN for TUM-CSE, winter 2010/2011

29

Interfaces

  • Specification of behaviour for usage outside.
  • At first glance, interfaces are similar to classes.
  • However, they do not include method bodies.
  • Hence, they are similar to abstract classes with

abstract methods only.

  • Properties:

– Key word interface instead of class. – Abstract methods only, no constructors. – Public method signatures only, constant fields only.

slide-30
SLIDE 30

Objects First with Java - A Practical Introduction using BlueJ, David J. Barnes, Michael Kölling; extensions by HJB&TN for TUM-CSE, winter 2010/2011

30

An Actor interface

public interface Actor { /** * Perform the actor's daily behaviour. * 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-31
SLIDE 31

Objects First with Java - A Practical Introduction using BlueJ, David J. Barnes, Michael Kölling; extensions by HJB&TN for TUM-CSE, winter 2010/2011

31

Classes implement an interface

public class Fox extends Animal implements Drawable { ... } public class Hunter implements Actor, Drawable { ... } extend for class inheritance, implement for interface inheritance.

Extend at most one class, implement any number of interfaces!

Animal stays a class –it contains concrete methods with bodies!

slide-32
SLIDE 32

Objects First with Java - A Practical Introduction using BlueJ, David J. Barnes, Michael Kölling; extensions by HJB&TN for TUM-CSE, winter 2010/2011

32

Interfaces as types

  • What’s the gain if no code is

implemented to be inherited?

  • Implementing classes do not inherit

code, but ...

  • ... implementing classes are subtypes
  • f the interface type.
  • So, polymorphism is available with

interfaces as well as classes.

slide-33
SLIDE 33

Objects First with Java - A Practical Introduction using BlueJ, David J. Barnes, Michael Kölling; extensions by HJB&TN for TUM-CSE, winter 2010/2011

33

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

Objects First with Java - A Practical Introduction using BlueJ, David J. Barnes, Michael Kölling; extensions by HJB&TN for TUM-CSE, winter 2010/2011

34

Alternative implementations

slide-35
SLIDE 35

Objects First with Java - A Practical Introduction using BlueJ, David J. Barnes, Michael Kölling; extensions by HJB&TN for TUM-CSE, winter 2010/2011

35

Review

  • Inheritance can provide shared

implementation.

– Concrete and abstract classes.

  • Inheritance provides shared type

information.

– Classes and interfaces.

slide-36
SLIDE 36

Objects First with Java - A Practical Introduction using BlueJ, David J. Barnes, Michael Kölling; extensions by HJB&TN for TUM-CSE, winter 2010/2011

36

Review

  • Abstract methods allow static type

checking without requiring implementation.

  • Abstract classes function as

incomplete superclasses.

– No instances.

  • Abstract classes support

polymorphism.

slide-37
SLIDE 37

Objects First with Java - A Practical Introduction using BlueJ, David J. Barnes, Michael Kölling; extensions by HJB&TN for TUM-CSE, winter 2010/2011

37

Interfaces

  • Interfaces provide specification

without implementation.

– Interfaces are fully abstract.

  • Interfaces support polymorphism.
  • Java interfaces support multiple

inheritance.