Chapter 11 : Modeling with Abstraction

Download Report

Transcript Chapter 11 : Modeling with Abstraction

An Introduction to Programming and Object Oriented Design using Java

3 rd Edition. Dec 2007

Jaime Niño Frederick Hosch

Chapter 11 : Modeling with Abstraction

Review of Player interface

   Interface

Player

implemented by several classes classes are identical except for implementation of takeTurn.

classes contain considerable amount of duplicate code.

«interface»

Player

Dec 2007

TimidPlayer Gr eedyPlayer

NH-Chapter 11:An Introduction To Programming And Object Oriented Design Using Java

CleverPlayer

1

Abstract classes

«i nterface»

Pl ayer

AbstractP layer Timi dP layer Gr eedyPlayer CleverP layer

 

AbstractPlayer

can contain implementations of methods common to all Player variants,  name  sticksTaken Player subclasses inherit these methods.

Dec 2007 NH-Chapter 11:An Introduction To Programming And Object Oriented Design Using Java 2

Abstract classes

 An abstract class is a class that  can contain abstract methods,  cannot be instantiated.

 used as basis on which to build classes by extension.

Dec 2007 NH-Chapter 11:An Introduction To Programming And Object Oriented Design Using Java 3

Abstract classes

  An abstract class is a class:  Defines a type.

 Occupies a position in the class hierarchy.

 Can be the parent of other classes, abstract or not.

 Has a unique parent which may or may not be abstract.

 Has one or more constructors.

 It can define nonabstract methods.

 Has instance variables.

Concrete class: a non-abstract class.

Dec 2007 NH-Chapter 11:An Introduction To Programming And Object Oriented Design Using Java 4

Abstract classes

 An abstract method must be labeled abstract.

public abstract void

takeTurn (Pile pile,

int

maxOnATurn);  An abstract class can inherit abstract methods  From an interface, or  From a class.

Dec 2007 NH-Chapter 11:An Introduction To Programming And Object Oriented Design Using Java 5

Interfaces, abstract classes and concrete classes

 An interface  used to specify functionality required by a client.

 An abstract class  provides a basis on which to build concrete servers.

 A concrete class  completes server implementation specified by an interface;  furnish run-time objects;  not generally suited to serve as a basis for extension.

Dec 2007 NH-Chapter 11:An Introduction To Programming And Object Oriented Design Using Java 6

Nim game , Interfaces, abstract classes andconcrete classes

 In the nim game,  Interface

Player

player for the defines functionality required by a

Game

and user interface.

 Abstract class AbstractPlayer contain implementation of methods common to all Player variants.

TimidPlayer

of ,

GreedyPlayer

,

AbstractPlayer

complete implementation of

ClerverPlayer

, subclasses , are concrete classes which

Player

interface.

Dec 2007 NH-Chapter 11:An Introduction To Programming And Object Oriented Design Using Java 7

Nim game , Interfaces, abstract classes andconcrete classes

 In the nim game,  Class

Game

is programmed using

Player

interface.

 During execution, instances of

ClerverPlayer.

Game

is provided with concrete

TimidPlayer

,

GreedyPlayer

, or Dec 2007 NH-Chapter 11:An Introduction To Programming And Object Oriented Design Using Java 8

Abstract class use

 An abstract class factors out implementation of its concrete subclasses.

 Used to exploit polymorphism.

 Functionality specified in parent class can be given implementations appropriate to each concrete subclass.

 Abstract class must be stable.

 any change in an abstract class propagates to subclasses and their clients.

 A concrete class can only extend one (abstract) class Dec 2007 NH-Chapter 11:An Introduction To Programming And Object Oriented Design Using Java 9

Interface use

 Interfaces are by definition abstract.

 separate an object’s implementation from its specification.

 they do not fix any aspect of an implementation.

 A class can implement more than one interface.

 Interfaces allow a more generalized use can be treated as identical for some specific purpose.

of polymorphism; instances of relatively unrelated classes Dec 2007 NH-Chapter 11:An Introduction To Programming And Object Oriented Design Using Java 10

Interfaces, abstract classes, concrete classes

«interface»

Depictable ArtClip GeometricalFigure

WordBalloon Rectangle public boolean

… isIn (Location point, Depictable figure) { Location l = figure.location(); Dimension d = figure.dimension(); }  Can pass instances of WordBalloon to

isIn

.

Dec 2007 NH-Chapter 11:An Introduction To Programming And Object Oriented Design Using Java 11

Specifying a class for extension

 Two class uses:  A class can be a client to another class and use it as a server.

 A class can also extend another class, using the other class as a basis for its implementation.

Dec 2007 NH-Chapter 11:An Introduction To Programming And Object Oriented Design Using Java 12

Specifying a class for extension

 Clients and subclasses have different views of a class.

uses

Cl ient SomeClass SubClass

Needs to know only specification of SomeClass Dec 2007 Needs to know specification and implementation of SomeClass NH-Chapter 11:An Introduction To Programming And Object Oriented Design Using Java 13

abstract class

AbstractPlayer

implements

Player {

private

String name;

private int

sticksTaken; //subclasses update it.

public

AbstractPlayer (String name) {

this

.name = name;

this

.sticksTaken = 0; }

public

String name () {

return this

.name; }

public int

sticksTaken () {

return this

.sticksTaken; }

public

String toString () {

return

"Player: " + name + ", took: " + sticksTaken; } } Dec 2007 NH-Chapter 11:An Introduction To Programming And Object Oriented Design Using Java 14

TimidPlayer definition via inheritance class

TimidPlayer

extends

AbstractPlayer {

public

TimidPlayer (String name) {

super

(name); }

public void

takeTurn (Pile pile,

int

maxOnATurn) { pile.remove(1);

this

.sticksTaken = 1; // updates of AbstractPlayer // instance variable.

} }  Will not compile.

TimidPlayer AbstractPlayer

has no access to instance variable sticksTaken.

Dec 2007 NH-Chapter 11:An Introduction To Programming And Object Oriented Design Using Java 15

Protected instance variables

abstract class

AbstractPlayer

implements

Player {

private

String name;

protected int

sticksTaken; … }  Now

TimidPlayer

has access to variable sticksTaken.

AbstractPlayer

instance Dec 2007 NH-Chapter 11:An Introduction To Programming And Object Oriented Design Using Java 16

Specifying a class for extension

 Root of

TimidPlayer

: problem between

AbstractPlayer

and  subclass has a different, stronger relation to parent class than a client.

 TimidPlayer needs to be able to tell AbstractPlayer “store this

sticksTaken

value.”  Subclasses needs a different contract” with its parent than a client needs.

 Use protected features to specify subclass contract.

Dec 2007 NH-Chapter 11:An Introduction To Programming And Object Oriented Design Using Java 17

Planning for extension

 A subclass depends on the Parent implementation.

 subclass often requires access to parent’s underlying implementation structure.

 correctness of a subclass can depend on the algorithms used to implement parent methods.

Dec 2007 NH-Chapter 11:An Introduction To Programming And Object Oriented Design Using Java 18

Planning for extension

public class

ThreeDigitLock A combination lock with a three digit combination.

public void

enterDigit (

int

digit) Enter a digit of the combination; lock unlocks if the three digits of the combination are entered in order.

require:

0 <= digit && digit <= 9

public void

enterCombination ( lock unlocks if the three

int

combination) Enter the three digit combination specified; digits of the combination are entered in order.

require:

0 <= combination && combination <= 999 Dec 2007 NH-Chapter 11:An Introduction To Programming And Object Oriented Design Using Java 19

Planning for extension

 Build lock that keeps track of total number of digits entered.

public class

InstrumentedLock

extends

ThreeDigitLock {

private int

public

digitCount;

void super

enterDigit (

int

digit) { digitCount = digitCount + 1; .enterDigit(digit); }

public void

enterCombination (

int

combination) { digitCount = digitCount + 3;

super

.enterCombination(combination); } … } Dec 2007 NH-Chapter 11:An Introduction To Programming And Object Oriented Design Using Java 20

Planning for extension

public class

public

ThreeDigitLock {

void int

enterCombination (

int

remainder = combination; combination) { ¹

int

position = 100;

while

(position > 0) { enterDigit(remainder / position); remainder = remainder % position; position = position / 10; } } … }  Problem:

ThreeDigitLock

’s enterCombination method is implementing by invoking enterDigit three times.

Dec 2007 NH-Chapter 11:An Introduction To Programming And Object Oriented Design Using Java 21

Planning for extension

 Due to implementation

ThreeDigitClass

class, increment digitCount.

of

enterCombination

InstrumentedLock

should in not 

InstrumentedLock

subclass design depends

ThreeDigitClass

’s algorithm used in enterCombination.

on 

ThreeDigitLock

must document method implementation.

Dec 2007 NH-Chapter 11:An Introduction To Programming And Object Oriented Design Using Java 22

Planning for extension

public void

enterCombination ( are entered in order.

int

combination) Enter the three digit combination specified; lock unlocks if the three digits of the combination This implementation invokes enterDigit three times, once for each digit in the specified combination.

require:

0 <= combination && combination <= 999 Dec 2007 NH-Chapter 11:An Introduction To Programming And Object Oriented Design Using Java 23

Planning for extension

 General rules to design classes for extension:  Document any internal use of class’s overridable methods.

 Constructors should not invoke class’s overridable methods .

Dec 2007 NH-Chapter 11:An Introduction To Programming And Object Oriented Design Using Java 24

Planning for extension

 Prevent class extension by declaring a class

final

.

public final class

ThreeDigitLock { …  Prevent method overriding by declaring method

final

.

public final void

enterCombination (

int

combination) { … Dec 2007 NH-Chapter 11:An Introduction To Programming And Object Oriented Design Using Java 25

Planning for extension

  Prevent extension of a class by declaring its constructor private. private constructor: lets us control the conditions under which an instance will be created.

public class

Singleton {

private static

Singleton instance =

null

; // constructor can be invoked only //from inside class.

private

Singleton () {}

public static

// if one doesn’t already exist, create it.

if

(instance == instance = new Singleton();

return

Singleton getInstance () { instance;

null

) } … } Dec 2007 NH-Chapter 11:An Introduction To Programming And Object Oriented Design Using Java 26

Composition revisited

 Uses of composition  a component is an intrinsic part of an object.

 a class formed as an aggregation of components, where components exist independently of aggregation.

 to “wrap” an existing class in order to alter its interface.

Dec 2007 NH-Chapter 11:An Introduction To Programming And Object Oriented Design Using Java 27

Class extension OR class composition?

«interface»

Player

AbstractPlayer

Dec 2007

TimidStrategy Player GreedyStrategy

has-a

CleverStrategy «interface»

PlayStrategy

TimidStrategy GreedyStrategy

NH-Chapter 11:An Introduction To Programming And Object Oriented Design Using Java

CleverStrategy

28

Class extension v.s. class composition

Extension

Composition

Reused class

superclass core class

Resulting class

subclass composed class Dec 2007 NH-Chapter 11:An Introduction To Programming And Object Oriented Design Using Java 29

Class extension v.s. class composition

 Two advantages of class extension  code reuse  polymorphism.

 Disadvantages of class extension  Changes to a superclass specification propagate to clients and subclasses  classes are not always designed and documented for extension.

 a subclass is committed to maintain specifications inherited from its superclass.

Dec 2007 NH-Chapter 11:An Introduction To Programming And Object Oriented Design Using Java 30

Class extension v.s. class composition

 Advantages of composition  Existing classes can be used in composed classes.

 Can change object’s behavior dynamically.

 Supports inheritance.

stronger encapsulation than does  Can change specification of composed class without changing core.

 Composed class depends only on specification of core class, not on its implementation.

Dec 2007  Implementation changes in core class do not propagate to composed class.

NH-Chapter 11:An Introduction To Programming And Object Oriented Design Using Java 31

Class extension v.s. class composition

«i nterface»

Lock

Instr um entedLock

wraps

ThreeDigitLock

 InstrumentedLock does not depend on implementation of ThreeDigitLock.

Dec 2007 NH-Chapter 11:An Introduction To Programming And Object Oriented Design Using Java 32

Class extension v.s. class composition

deal

()

Dealer

wraps

Player

 Composition can add functionality to an object.

Dec 2007 NH-Chapter 11:An Introduction To Programming And Object Oriented Design Using Java 33

Class extension v.s. class composition

 Conclusion:  reuse through composition produces more flexible code.

 must not ignore advantages of polymorphism via inheritance.

 lose polymorphism with composition.

 But can gain it back by composing with interfaces and defining core classes that implement them.

Dec 2007 NH-Chapter 11:An Introduction To Programming And Object Oriented Design Using Java 34

Extension, composition, and modifying functionality

 Poor use of extension : to model

roles

objects play.

 Results in awkward constructions in which detailed knowledge of an object’s possible roles is spread throughout the application.

Dec 2007 NH-Chapter 11:An Introduction To Programming And Object Oriented Design Using Java 35

Extension, composition, and modifying functionality

 Poor use of extension : model

roles

objects may play.

  Example: model card player, and card dealer.

Solution:  specify Player  use extension to specify Dealer.

 Problem: change Player role to Dealer role (and vice versa).

 Solution (Ackward) : Make any Player an instance of Dealer. Switch roles via Dealer state condition.

Dec 2007 NH-Chapter 11:An Introduction To Programming And Object Oriented Design Using Java 36

Extension, composition, and modifying functionality

 Good use of composition : to model play.

roles

objects may   Example: model card player, and card dealer.

Solution:  specify Player  specify Dealer having a Player as a component.

  Problem: change Player role to Dealer role (and vice versa).

Solution: Dealer can be assigned Player at run-time.

Dec 2007 NH-Chapter 11:An Introduction To Programming And Object Oriented Design Using Java 37

Extension, composition, and modifying functionality

 Poor use of extension: implementations of functionality.

provide alternate  can lead to a combinatorial explosion in class hierarchy

AbstractPlayer

TimidPlayer CleverPlayer

Dec 2007

WageringTimidPlayer BlufferTimidPlayer

NH-Chapter 11:An Introduction To Programming And Object Oriented Design Using Java … 38

Extension, composition, and modifying functionality

 Good use of composition: implementations of functionality.

provide alternate  Bridge pattern: Separate abstraction hierarchy from implementation hierarchy.

has implementation

SomeClass void

service()

Implementation

void

service() implementation.service();

Extension1

Dec 2007

Extension2 Implementation1

NH-Chapter 11:An Introduction To Programming And Object Oriented Design Using Java

Implementation2

39

Extension and object state

  “Kind” of thing object models and object “state” are related.

Model several categories of students: junior division students, undergraduates, graduate students, etc.

public class

Student { … // Student classifications:

public static final int

JUNIOR_DIVISION = 0;

public static final int public static final int private int

public int

UNDERGRADUATE = 1; GRADUATE = 2; classification; …

public void

classification () { … setClassification ( }

int

… class) { … } Dec 2007 NH-Chapter 11:An Introduction To Programming And Object Oriented Design Using Java } 40

Extension and object state

 Some of the functionality of a dependent.

Student

is state  Code depending on student’s classification via case analysis.

int if

classification = someStudent.classification(); (classification == Student.JUNIOR_DIVISION) {

handle JUNIOR_DIVISION case …

}

else if

handle UNDERGRADUATE case …

(classification == Student.UNDERGRADUATE) { }

else if

(classification == Student.GRADUATE){ Dec 2007 NH-Chapter 11:An Introduction To Programming And Object Oriented Design Using Java 41

Extension and object state

 Problem with structure:  method containing this code is dependent on student classifications.

 such structured implementation.

conditionals scattered throughout  maintenance complication: adding new classification requires modifications in a number of places,.

 long conditionals handling many cases are hard to understand and difficult to modify or extend.

 Such structures are generally undesirable in an object-oriented system.

Dec 2007 NH-Chapter 11:An Introduction To Programming And Object Oriented Design Using Java 42

Extension and object state

 Better structure: subclass classifications.

Student

to model different  Classification-dependent behavior handled by providing different implementations in subclass methods.

 New classification is handled by defining a new subclass.

 Clients depend on polymorphism for appropriate behavior.

Dec 2007 NH-Chapter 11:An Introduction To Programming And Object Oriented Design Using Java 43

State as an object

 Difficulty with subclassing classification.

 Class of an object is fixed when the object is created.

 Subclassing (static) does not support (dynamic) type transfer from one subclass to another.

Dec 2007 NH-Chapter 11:An Introduction To Programming And Object Oriented Design Using Java 44

State as an object

 Better structuring of Student with classification that changes dynamically:  Define interface isolating state-dependent behavior.

 Equip object with a state-defining component that implements interface.

 Different behaviors achieved by providing different subclasses for component.

Dec 2007  State-dependent component.

requests forwarded NH-Chapter 11:An Introduction To Programming And Object Oriented Design Using Java to state 45

State as an object

Student

classification

«interface»

Classification

JuniorDivision Undergraduate

Dec 2007 NH-Chapter 11:An Introduction To Programming And Object Oriented Design Using Java 46