An Introduction to Programming and Object Oriented Design

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

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

Review of Player interface ñ Interface Player implemented by several classes ñ classes are identical except for implementation of take. Turn. ñ classes contain considerable amount of duplicate code. May 2004 NH-Chapter 11 2

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

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

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

Abstract classes ñ An abstract method must be labeled abstract. public abstract void take. Turn (Pile pile, int max. On. ATurn); ñ An abstract class can inherit abstract methods ñ From an interface, or ñ From a class. May 2004 NH-Chapter 11 6

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

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 Abstract. Player contain implementation of methods common to all Player variants. ñ Timid. Player, Greedy. Player, Clerver. Player, subclasses of Abstract. Player, are concrete classes which complete implementation of Player interface. May 2004 NH-Chapter 11 8

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 Timid. Player, Greedy. Player, or Clerver. Player. May 2004 NH-Chapter 11 9

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

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

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

Interfaces, abstract classes, concrete classes «interface» Depictable Geometrical. Figure Rectangle public boolean is. In (Location point, Depictable figure) { Location l = figure. location(); Dimension d = figure. dimenstion(); … } ñ Can pass instances of Word. Balloon to is. In. May 2004 NH-Chapter 11 13

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

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

abstract class Abstract. Player implements Player { private String name; private int sticks. Taken; //subclasses will update it. public Abstract. Player (String name) { this. name = name; this. sticks. Taken = 0; } public String name () { return this. name; } public int sticks. Taken () { return this. sticks. Taken; } public String to. String () { return "Player: " + name + ", took: " +sticks. Taken; } } May 2004 NH-Chapter 11 16

class Timid. Player extends Abstract. Player { public Timid. Player (String name) { super(name); } public void take. Turn (Pile pile, int max. On. ATurn) { pile. remove(1); this. sticks. Taken = 1; // update of Abstract. Player // instance variable. } } ñ Will not compile. ñ Timid. Player has no access to Abstract. Player instance variable sticks. Taken. May 2004 NH-Chapter 11 17

abstract class Abstract. Player implements Player { private String name; protected int sticks. Taken; … } ñ Now Timid. Player has access to Abstract. Player instance variable sticks. Taken. May 2004 NH-Chapter 11 18

Specifying a class for extension ñ Root of problem between Abstract. Player and Timid. Player: ñ subclass has a different, stronger relation to parent class than a client. ñ Timid. Player needs to be able to tell Abstract. Player “store this sticks. Taken value. ” ñ Subclasses needs a different “contract” with its parent than a client needs. ñ Use protected features to specify subclass contract. May 2004 NH-Chapter 11 19

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

Planning for extension ñ Class has methods that allow combination entered either digit by digit, or a single integer. public class Three. Digit. Lock A combination lock with a three digit combination. public void enter. Digit (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 enter. Combination (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 May 2004 NH-Chapter 11 21

Planning for extension ñ Build lock that keeps track of total number of digits entered. public class Instrumented. Lock extends Three. Digit. Lock { private int digit. Count; … public void enter. Digit (int digit) { digit. Count = digit. Count + 1; super. enter. Digit(digit); } public void enter. Combination (int combination) { digit. Count = digit. Count + 3; super. enter. Combination(combination); } … } May 2004 NH-Chapter 11 22

Planning for extension ñ Problem: Three. Digit. Lock’s enter. Combination method is implementing by invoking enter. Digit three times: public class Three. Digit. Lock { … public void enter. Combination (int combination) { int remainder = combination; int position = 100; while (position > 0) { ¹ enter. Digit(remainder / position); remainder = remainder % position; position = position / 10; } } … } May 2004 NH-Chapter 11 23

Planning for extension ñ Due to implementation of enter. Combination in Three. Digit. Class class, Instrumented. Lock should not increment digit. Count. ñ Instrumented. Lock subclass design depends on Three. Digit. Class’s algorithm used in enter. Combination. ñ Three. Digit. Lock must document method implementation. May 2004 NH-Chapter 11 24

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

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

Planning for extension ñ Prevent class extension by declaring a class final. public final class Three. Digit. Lock { … ñ Prevent method overriding by declaring method final. public final void enter. Combination (int combination) {… May 2004 NH-Chapter 11 27

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

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

Class extension OR class composition? «interface» Player Abstract. Player Timid. Strategy Player Greedy. Strategy has-a «interface» Play. Strategy Timid. Strategy May 2004 Clever. Strategy Greedy. Strategy NH-Chapter 11 Clever. Strategy 30

Class extension v. s. class composition Reused class Resulting class Extension superclass subclass Composition core class composed class May 2004 NH-Chapter 11 31

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

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

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

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

Class extension v. s. class composition ñ Instrumented. Lock does not implementation of Three. Digit. Lock. May 2004 NH-Chapter 11 depend on 36

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

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

Extension, composition, and modifying functionality b. Poor 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. May 2004 NH-Chapter 11 39

Extension, composition, and modifying functionality b Poor 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). b Solution (Ackward) : Make any Player an instance of Dealer. Switch roles via Dealer state condition. May 2004 NH-Chapter 11 40

Extension, composition, and modifying functionality a. Good 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). a. Solution: Dealer instance can be assigned object Player at run -time. May 2004 NH-Chapter 11 41

Extension, composition, and modifying functionality b. Poor use of extension: provide implementations of functionality. alternate acan lead to a combinatorial explosion in class hierarchy Abstract. Player Timid. Player Wagering. Timid. Player May 2004 Clever. Player Bluffer. Timid. Player NH-Chapter 11 42

Extension, composition, and modifying functionality a. Good use of composition: provide alternate implementations of functionality. a. Bridge pattern: Separate abstraction hierarchy from implementation hierarchy. Some. Class has implementation void service() Implementation void service() implementation. service(); Extension 1 May 2004 Extension 2 Implementation 1 NH-Chapter 11 Implementation 2 43

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 set. Classification (int class) { … } May 2004 NH-Chapter 11 44

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 = some. Student. classification(); if (classification == Student. JUNIOR_DIVISION) { handle JUNIOR_DIVISION case } else if (classification == Student. UNDERGRADUATE) { handle UNDERGRADUATE case } else if (classification == Student. GRADUATE) … May 2004 NH-Chapter 11 45

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 difficult to modify or extend. ñ Such structures are generally undesirable in an object-oriented system. May 2004 NH-Chapter 11 46

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

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

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

State as an object Student classification «interface» Classification … Junior. Division May 2004 NH-Chapter 11 Undergraduate 50

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

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

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

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

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