Presentation is loading. Please wait.

Presentation is loading. Please wait.

An Introduction to Programming and Object Oriented Design using Java 2 nd Edition. May 2004 Jaime Niño Frederick Hosch Chapter 11 : Modeling with Abstraction.

Similar presentations


Presentation on theme: "An Introduction to Programming and Object Oriented Design using Java 2 nd Edition. May 2004 Jaime Niño Frederick Hosch Chapter 11 : Modeling with Abstraction."— Presentation transcript:

1 An Introduction to Programming and Object Oriented Design using Java 2 nd Edition. May 2004 Jaime Niño Frederick Hosch Chapter 11 : Modeling with Abstraction

2 1May 2004NH-Chapter 11 Objectives ñAfter studying this chapter you should understand the following: ñthe roles played by interfaces, abstract classes, and concrete classes; ñthe use of protected features for the benefit of subclasses; ñthe two kinds of clients a class can have, and the additional documentation required by subclass clients regarding the implementation of superclass features; ñclass extension and class composition, and their proper use. ñAlso, you should be able to: ñuse abstract classes to specify class generalization; ñuse interfaces, abstract classes, and concrete classes to model a system.

3 2May 2004NH-Chapter 11 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.

4 3May 2004NH-Chapter 11 Abstract classes ñAbstractPlayer can contain implementations of methods common to all Player variants,  name  sticksTaken ñPlayer subclasses inherit these methods.

5 4May 2004NH-Chapter 11 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.

6 5May 2004NH-Chapter 11 Abstract classes ñAn abstract class is 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.

7 6May 2004NH-Chapter 11 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.

8 7May 2004NH-Chapter 11 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.

9 8May 2004NH-Chapter 11 Nim game, Interfaces, abstract classes andconcrete classes ñIn the nim game, ñInterface Player defines functionality required by a player for the Game and user interface. ñAbstract class AbstractPlayer contain implementation of methods common to all Player variants. ñ TimidPlayer, GreedyPlayer, ClerverPlayer, subclasses of AbstractPlayer, are concrete classes which complete implementation of Player interface.

10 9May 2004NH-Chapter 11 Nim game, Interfaces, abstract classes andconcrete classes ñIn the nim game, ñClass Game is programmed using Player interface. ñDuring execution, Game is provided with concrete instances of TimidPlayer, GreedyPlayer, or ClerverPlayer.

11 10May 2004NH-Chapter 11 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

12 11May 2004NH-Chapter 11 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 of polymorphism; instances of relatively unrelated classes can be treated as identical for some specific purpose.

13 12May 2004NH-Chapter 11 Interfaces, abstract classes, concrete classes Depictable «interface» Rectangle GeometricalFigure public boolean isIn (Location point, Depictable figure) { Location l = figure.location(); Dimension d = figure.dimenstion(); … }

14 13May 2004NH-Chapter 11 Interfaces, abstract classes, concrete classes public boolean isIn (Location point, Depictable figure) { Location l = figure.location(); Dimension d = figure.dimenstion(); … } Depictable «interface» Rectangle GeometricalFigure  Can pass instances of WordBalloon to isIn.

15 14May 2004NH-Chapter 11 Specifying a class for extension ñTwo class uses: ñA class can be a client to another class and use the other class as a server. ñA class can also extend another class, using the other class as a basis for its implementation.

16 15May 2004NH-Chapter 11 Specifying a class for extension ñClients and subclasses have different views of a class. Needs to know only specification of SomeClass Needs to know specification and implementation of SomeClass

17 16May 2004NH-Chapter 11 abstract class AbstractPlayer implements Player { private String name; private int sticksTaken; //subclasses will 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; }

18 17May 2004NH-Chapter 11 class TimidPlayer extends AbstractPlayer { public TimidPlayer (String name) { super(name); } public void takeTurn (Pile pile, int maxOnATurn) { pile.remove(1); this.sticksTaken = 1; // update of AbstractPlayer // instance variable. } ñWill not compile.  TimidPlayer has no access to AbstractPlayer instance variable sticksTaken.

19 18May 2004NH-Chapter 11 abstract class AbstractPlayer implements Player { private String name; protected int sticksTaken; … }  Now TimidPlayer has access to AbstractPlayer instance variable sticksTaken.

20 19May 2004NH-Chapter 11 Specifying a class for extension ñRoot of problem between AbstractPlayer and TimidPlayer: ñ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.

21 20May 2004NH-Chapter 11 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.

22 21May 2004NH-Chapter 11 Planning for extension ñClass has methods that allow combination entered either digit by digit, or a single integer. 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 (int combination) Enter the three digit combination specified; lock unlocks if the three digits of the combination are entered in order. require: 0 <= combination && combination <= 999

23 22May 2004NH-Chapter 11 Planning for extension ñBuild lock that keeps track of total number of digits entered. public class InstrumentedLock extends ThreeDigitLock { private int digitCount; … public void enterDigit (int digit) { digitCount = digitCount + 1; super.enterDigit(digit); } public void enterCombination (int combination) { digitCount = digitCount + 3; super.enterCombination(combination); } … }

24 23May 2004NH-Chapter 11 Planning for extension  Problem: ThreeDigitLock’s enterCombination method is implementing by invoking enterDigit three times: public class ThreeDigitLock { … public void enterCombination (int combination) { int remainder = combination; int position = 100; while (position > 0) { ¹enterDigit(remainder / position); remainder = remainder % position; position = position / 10; } … }

25 24May 2004NH-Chapter 11 Planning for extension  Due to implementation of enterCombination in ThreeDigitClass class, InstrumentedLock should not increment digitCount.  InstrumentedLock subclass design depends on ThreeDigitClass ’s algorithm used in enterCombination. ñThreeDigitLock must document method implementation.

26 25May 2004NH-Chapter 11 Planning for extension public void enterCombination (int combination) Enter the three digit combination specified; lock unlocks if the Three digits of the combination are entered in order. This implementation invokes enterDigit three times, once for each digit in the specified combination. require: 0 <= combination && combination <= 999

27 26May 2004NH-Chapter 11 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.

28 27May 2004NH-Chapter 11 Planning for extension ñPrevent class extension by declaring a class final. ñPrevent method overriding by declaring method final. public final class ThreeDigitLock { … public final void enterCombination (int combination) {…

29 28May 2004NH-Chapter 11 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.

30 29May 2004NH-Chapter 11 Class extension and class composition

31 30May 2004NH-Chapter 11 Class extension OR class composition? PlayStrategy «interface» GreedyStrategyCleverStrategyTimidStrategy Player has-a Player «interface» AbstractPlayer GreedyStrategyCleverStrategyTimidStrategy

32 31May 2004NH-Chapter 11 Class extension v.s. class composition Reused classResulting class Extensionsuperclasssubclass Compositioncore classcomposed class

33 32May 2004NH-Chapter 11 Class extension v.s. class composition ñTwo advantages of class extension acode reuse apolymorphism.

34 33May 2004NH-Chapter 11 Class extension v.s. class composition ñDisadvantages of class extension  Changes to a superclass specification propagate to clients and subclasses

35 34May 2004NH-Chapter 11 Class extension v.s. class composition ñOther disadvantages of class extension bclasses are not always designed and documented for extension. ba subclass is committed to maintain specifications inherited from its superclass.

36 35May 2004NH-Chapter 11 Class extension v.s. class composition ñAdvantages of composition aExisting classes can be used in composed classes. a Can change object’s behavior dynamically. aSupports stronger encapsulation than does inheritance. aCan change specification of composed class without changing core. aComposed class depends only on specification of core class, not on its implementation. aImplementation changes in core class do not propagate to composed class.

37 36May 2004NH-Chapter 11 Class extension v.s. class composition ñInstrumentedLock does not depend on implementation of ThreeDigitLock.

38 37May 2004NH-Chapter 11 Class extension v.s. class composition  Composition can add functionality to an object.

39 38May 2004NH-Chapter 11 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.

40 39May 2004NH-Chapter 11 Extension, composition, and modifying functionality bPoor use of extension : to model roles objects play. bresult in awkward constructions in which detailed knowledge of an object’s possible roles is spread throughout the application.

41 40May 2004NH-Chapter 11 Extension, composition, and modifying functionality bPoor use of extension : model roles objects may play. ñExample: model card player, and card dealer. ñSolution: aspecify Player buse extension to specify Dealer. ñProblem: change Player role to Dealer role (and vice-versa). bSolution (Ackward) : Make any Player an instance of Dealer. Switch roles via Dealer state condition.

42 41May 2004NH-Chapter 11 Extension, composition, and modifying functionality aGood use of composition : to model roles objects may play. ñExample: model card player, and card dealer. ñSolution: aspecify Player aspecify Dealer having a Player instance as a component. ñProblem: change Player role to Dealer role (and vice-versa). aSolution: Dealer instance can be assigned object Player at run-time.

43 42May 2004NH-Chapter 11 Extension, composition, and modifying functionality bPoor use of extension: provide alternate implementations of functionality. acan lead to a combinatorial explosion in class hierarchy CleverPlayerTimidPlayer AbstractPlayer WageringTimidPlayerBlufferTimidPlayer

44 43May 2004NH-Chapter 11 Extension, composition, and modifying functionality aGood use of composition: provide alternate implementations of functionality. aBridge pattern: Separate abstraction hierarchy from implementation hierarchy. SomeClass has implementation void service() implementation.service(); Extension1Extension2 Implementation void service() Implementation1Implementation2

45 44May 2004NH-Chapter 11 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 UNDERGRADUATE = 1; public static final int GRADUATE = 2; private int classification; … public int classification () { … } … public void setClassification (int class) { … } … }

46 45May 2004NH-Chapter 11 Extension and object state ñSome of the functionality of a Student is state dependent. ñCode depending on student’s classification via case analysis. int classification = someStudent.classification(); if (classification == Student.JUNIOR_DIVISION) { handle JUNIOR_DIVISION case } else if (classification == Student.UNDERGRADUATE) { handle UNDERGRADUATE case } else if (classification == Student.GRADUATE) …

47 46May 2004NH-Chapter 11 Extension and object state ñProblem with structure: ñmethod containing this code is dependent on student classifications. ñsuch structured conditionals scattered throughout implementation. ñ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.

48 47May 2004NH-Chapter 11 Extension and object state ñBetter structure: subclass Student to model different classifications. ñ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.

49 48May 2004NH-Chapter 11 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.

50 49May 2004NH-Chapter 11 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. ñState-dependent requests forwarded to state component.

51 50May 2004NH-Chapter 11 State as an object Classification Undergraduate «interface» JuniorDivision Student classification …

52 51May 2004NH-Chapter 11 Summary ñconsidered use abstraction and composition in the structure of a system design. ñIntroduced abstract classes. ñcan contain abstract methods, ñcannot be instantiated. ñcontains an implementation component ñForm part of a class hierarchy. ñused as a foundation on which to build concrete classes.

53 52May 2004NH-Chapter 11 Summary ñClasses have two distinct kinds of “customers”: ñclients that use class through its specification. ñsubclasses that extend the class. ñDifferent kinds of customers ñhave very different needs, ñRequire different class contracts.

54 53May 2004NH-Chapter 11 Summary ñDependency of subclass on parent superclass ñquite strong, ñat the implementation level. ñGood rule: view only abstract classes and interfaces as suitable for extension.

55 54May 2004NH-Chapter 11 Summary ñCompared composition and extension. ñcould achieve alternate implementations either by extending class, or by providing class with a “strategy” component. ñFunctionality can be added to a class with extension or by wrapping. ñComposition: ñfewer maintenance problems than extension. ñproduces a more flexible and maintainable structure than extension. ñExtension ñfor legitimate, permanent is-a relation between classes, ñ specification of the superclass is stable.

56 55May 2004NH-Chapter 11 Summary ñObject state can be modeled with extension. ñCases where object can dynamically change state, use composition with state component structured via inheritance


Download ppt "An Introduction to Programming and Object Oriented Design using Java 2 nd Edition. May 2004 Jaime Niño Frederick Hosch Chapter 11 : Modeling with Abstraction."

Similar presentations


Ads by Google