New User Special Price Expires in

Let's log you in.

Sign in with Facebook


Don't have a StudySoup account? Create one here!


Create a StudySoup account

Be part of our community, it's free to join!

Sign up with Facebook


Create your account
By creating an account you agree to StudySoup's terms and conditions and privacy policy

Already have a StudySoup account? Login here


by: Mrs. Maximo Lueilwitz
Mrs. Maximo Lueilwitz
GPA 3.95


Almost Ready


These notes were just uploaded, and will be ready to view shortly.

Purchase these notes here, or revisit this page.

Either way, we'll remind you when they're ready :)

Preview These Notes for FREE

Get a free preview of these Notes, just enter your email below.

Unlock Preview
Unlock Preview

Preview these materials now for free

Why put in your email? Get access to more of this material and other relevant free materials for your school

View Preview

About this Document

Class Notes
25 ?




Popular in Course

Popular in ComputerScienence

This 36 page Class Notes was uploaded by Mrs. Maximo Lueilwitz on Monday October 19, 2015. The Class Notes belongs to CS 582 at Oregon State University taught by Staff in Fall. Since its upload, it has received 12 views. For similar materials see /class/224501/cs-582-oregon-state-university in ComputerScienence at Oregon State University.

Similar to CS 582 at OSU


Reviews for OBJECT


Report this Material


What is Karma?


Karma is the currency of StudySoup.

You can buy or earn more Karma at anytime and redeem it for class notes, study guides, flashcards, and more!

Date Created: 10/19/15
Chapter 8 A Case Study Solitaire A program for playing the cart game solitaire will illustrate the utility and power of in heritance and overriding A major part of the game of Solitaire is moving cards from one card pile to another There are a number of different types of card piles each having some features in common with the others while other features are unique A common parent class CardPile can therefore be used to capture the common elements while inheritance and over riding can be used to produce specialized types of piles The developement of this program will illustrate how inheritance can be used to simplify the creation of these components and ensure that they can all be manipulated in a similar fashion 81 The Class Card To create a card game we rst need to de ne a class to represent a playing card Each instance of class Card Figure 841 maintains a suit value and a rank To prevent modi cation of these values the instance variables maintaining them are declared private and acce mediated through ac ssor functions The value of the suit and rank elds are set by the constructor for the class Integer constant values in Java de ned by the use of final static constants are de ned for the height and width of the card as well as for the sui Another function permits the user to determine the color of the card The Java library class Color is used to represent the color abstraction The Color class de nes constants for various colors The values Colorred Colorblack Coloryellow and Colorblue are used in the solitare progranL There are important reasons that data values representing suit and rank should be returned through an sor function as opposed to de ning the data elds 5 and r as public and allowing direct EM to the data values One of the most important is that access through a function ensures that the rank and suit characteristics of a card can be read but not altered once the card has been created IS n 99 100 CHAPTER 8 A CASE STUDY SOLITAIRE import java awt ak public class Card public constants for card Width and suits public final static int width 50 public final static int height 70 public final static int heart public final static int spade public final static int diamond public final static int clu internal data elds for rank and suit private boolean faceup private int r private int s 0 1 g constructor Card int sv int rv s sv r rv faceup false acccss attributes of card public int rank return r public int suit return s public boolean faceUp return faceup public void flip faceup faceup public Color color if faceUp if suit heart H suit diamond return Colorred else return Colorblack return Coloryellow public void draw Graphics g int x int y Figure 81 Description of the class cardl 82 THE GAME 101 The only other actions a card can perform besides setting and returning the state of the card are to ip over and to display itself The function flip is a one line function that simply reverses the value held by an instance variable The drawing function is more complex making use of the drawing facilities provided by the Java standard application library As we have seen in the earlier case studies the application library provides a data type called Graphics that provides a variety of methods for drawing lines and common shapes as well as for coloring An argument of this type is passed to the draw function as are the integer coordinates representing the upper left corner of the c39 rt The card images are simple line drawings as shown below Diamonds and hearts are drawn in red spades and clubs in black The hash marks on the back are drawn in yellow A portion of the procedure for drawing a playing card is shown in Figure 8 A 3 The most important feature of the playing card abstraction is the manner in which each card is responsible for maintaining within itself all card related information and behaviors The card knows both its value and how to draw itself In this manner the information is encapsulated and isolated from the application using the playing card If for example one were to move the program to a new platform using different graphics facilities only the draw method within the class itself would need to be altered 82 The Game The version of solitaire we will describe is known as klondikel The countles variations on this game make it probably the most common version of solitair so much so that when r solitaire quot most people think of klondike The version we will use is that described in 393 in the exercises we will explore some of the common variations The layout of the game is shown in Figure 84 4 A single standard pack of 52 cards is used The tableau or playing table consists of 28 cards in 7 pilesl the rst pile has 1 card the second 2 and so on up to 74 The top card of each pile is initially face up all other cards are face down The suit piles sometimes called foundations are built up from aces to kings in suits They are constructed above the tableau as the cards become available The object of the 102 CHAPTER 8 A CASE STUDY SOLITAIRE public class Card public void draw Graphics g int x int y String names nAn quot2quot quotan quot4quot x15quot quot6quot quot7quot quot8quot quot9quot quot10quot quotJquot quotan uku clear rectangle draw borer gclearRectx y width height gsetColorColorblue gdrawRectx y width height draw body of card gsetColorcolor if faceUp gdrawStrihghamesrahk x8 y15 if suit heart gdrawLinex25 y30 x35 y20 gdrawLinex35 y20 x45 y30 gdrawLinex45 y30 x25 y60 gdrawLinex25 y60 x5 y30 gdrawLihex5 y30 x15 y20 gdrawLinex15 y20 x25 y30 else if suit spade else if suit diamond else if suit club gdraw0valx20 y25 10 10 gdraw0valx25 y35 10 10 gdraw0valx15 y35 10 10 gdrawLinex23 y45 x20 y55 gdrawLinex20 y55 x30 y55 gdrawLihex80 y55 x27 y45 else face down gdrawLinex15 y5 x15 y65 gdrawLinex35 y5 x35 y65 gdrawLihex5 y20 x45 y20 gdrawLinex5 y35 x45 y35 gdrawLinex5 y50 x45 y50 Figure 82 Procedure to draw a playing card 82 THE GAME 103 Suit Piles DEED EEEEEE Figure 83 Layout for the solitaire game game is to build all 52 cards into the suit pilesi The cards that are not part of the tableau are initially all in the deck Cards in the deck are face down and are drawn one by one from the deck and placed face up on the discard pile From there they can be moved onto either a tableau pile or a foundation Cards are drawn from the until the pile is empty at this point the game is over if no further moves can be made Cards can be placed on a tableau pile only on a card of next higher rank and opposite colorx T V can be placed on a foundation only if they are the same suit and next higher card or if the foundation is empty and the card is an ace Spaces in the tableau that arise during play can be lled only by kings The topmost card of each tableau pile and the topmost card of the discard pile are alw s available for play The only time more than one card is moved is when an entire collt on of face up cards from a tableau called a build is moved to another tableau pilei This can be done if the bottommost card of the build can be legally played on the topmost card of C 104 CHAPTER 8 A CASE STUDY SOLITAIRE the destination Our initial game will not support the transfer of a build but we will discuss this as a possible extension The topmost card of a tableau is always face up If a card is moved from a tableau leaving a face down card on the top the latter card can be turned face up From this short description it is clear that the game of solitaire mostly involves manip ulating piles of cards Each type of pile has many features in common with the others and a few aspen s unique to the particular type In the next 1 tion we will investigate in detail how inheritance can be used in such circumstances to simplify the implementation of the various card piles by providing a common base for the generic actions and permitting this base to be rede ned when necessary 83 Card Piles Inheritance in Action Much of the behavior we associate with a card pile is common to each variety of pile in the game For example each pile maintains a collection of the cards in the pile held in a Stack and the operations of inserting and deleting elements from this collection are common Other operations are given default behavior in the class CardPile but they are sometimes overridden in the various subclasses The class CardPiIe is shown in Figure 84 Each card pile maintains the coordinate location for the upper left corner of the pile as well as a Stack The stack is used to hold the cards in the pile All three of these values are set by the constructor for the class The data elds are declared as protected and thus accessible to member functions associated with this class and to member functions associated with subclasses The three functions top pop and isEmpty manipulate the list of cards using func tions provided by the Stack utility cl 39 that these three methods have been declared as inal This modi er serves t important purposes First it is a documentation aid signaling to the reader of the listing that the methods cannot be overridden by subclasses Second in some situations the Java compiler can optimize the invocation of final methods creating faster code than could be generated for the execution of non nal methods The topmost card in a pile is returned by the function top This card will be the last card in the underlying container Note that the function peek provided by the Stack class returns a value declared as Object This result must be cast to a Card value before it can be returned as the result The method pop uses the pop operation provided by the underlying stack The stack method throws an exception if an attempt is made to remove an element from an empty stack The pop method in the class CardPile catches the exception and returns a null value in this situation The ve operations that are not declared final are common to the abstract notion of our card piles but they differ in details in each case For example the function canTa keCard asks whether it is legal to place a card on the given pilel A card can be added to a foundation pile for instance only if it is an ace and the foundation is empty or if the card is of the O H a g on on 83 CARD PILESVVVINHERITANCE IN ACTION 105 import javautilStack import javautilEmptyStackException public class CardPile protected int x coordinates of the card pile protected int y protected Stack thePile the collection of cards xl y yl thePile new Stack CardPile int xl int yl x public final Card top return Card thePilepeek public final boolean isEmpty return thePileempty public final Card pop try return Card thePilepop catch EmptyStackException e return null the following are sometimes overridden public boolean includes int tx int ty return x lt tx amp tx lt x Cardwidth ampamp y lt ty ampamp ty lt y Cardheight public void select int tx int ty public void addCard Card aCard thePilepushaCard public void display Graphics g gsetColorColorblue if isEmpty gdrawRectx y Cardwidth Cardheight else topdrawg x y public boolean canTake Card aCard return false Figure 84 Description of the class CardPile 106 CHAPTER 8 A CASE STUDY SOLITAIRE same suit as the current topmost card in the pile and has the next higher value A card can he added to a tahleau pile on the other hand only if the pile is empty and the card is a king or if it is of the opposite color as the current topmost card in the pile and has the next lower value The actions of the ve virtual functions de ned in CardPile can be characterized as follows includes reretermines if the coordinates given as arguments are contained within the bound aries of the pile The default action simply tests the topmost card this is overridden in the tableau piles to test all card values canTake wTells whether a pile can take a speci c cardt Only the tableau and suit piles can take cards so the default action is simply to return no this is overridden in the two classes mentioned addCard Adds a card to the card list It is rede ned in the discard pile class to ensure that the card is face up display Displays the card deck The default method merely displays the topmost card of the pile but is overridden in the tableau class to display a column of cards The top half of each hidden card is displayed So that the playing surface area is conserve only the topmost and hottommost face up cards are displayed this permits us to give de nite bounds to the playing surface 2 select wPerforms an action in response to a mouse click It is invoked when the user selects a pile V king the mouse in the portion of the playing eld covered by the pile The default ac ion does nothing but is overridden by the table deck and discard piles to play the topmost card if possible 3 4 The following table illustrates the important bene ts of inheritance Given ve oper ations and ve classes there are 25 potential methods we might have had to de ne By making use of inheritance we need to implement only 13 Furthermore we are guaranteed that each pile will respond in the same way to similar requests lCardPile SuitPile DeckPile DiscardPile TableauPile includes x x canTake x x x addCard x x display x x select x x x x 83 CARD FILESVVVINHERITANCE IN ACTION 107 class SuitPile extends CardPile SuitPile int x int y superx y public boolean canTake Card aCard if isEmpty return aCardrank 0 Card topCard top return aCardsuit topCardsuit ampamp aCardrank 1 topCardrank Figure 85 The class SuitPile 831 The Suit Piles We will examine each of the subclasses of CardPiIe in detail pointing out various uses of object oriented f tatures as they are encountered The simplest subclass is the class SuitPile shown in Figure which represents the pile of cards at the top of the playing surface the pile being built up in suit from ace to king The class SuitPiIe de nes only two methods The constructor for the class takes two integer arguments and does nothing more than invoke the constructor for the parent class CardPiIe Note the use of the keyword super to indicate the parent class The method canTake determines whether or not a card can be placed on the pile A card is legal if the pile is empty and the card is an ace that is has rank zero or if the card is the same suit as the topmost card in the pile and of the next higher rank for example a three of spades can only be played on a two of spades All other behavior of the suit pile is the same as that of our generic card pile When selected a suit pile does nothing When a card is added it is simply inserted into the collection of cards To display the pile only the topmost card is drawn 832 The Deck Pile The DeckPiIe Figure 86 maintains the original deck of cards It differs from the generic card pile in two ways When constructed rather than creating an empty pile of cards it creates the complete deck of 52 cards inserting them in order into the collection Once all the cards have been created the collection is then shu led To do this a random number generator is rst created This generator is provided by the Java utili y class Random A loop then examines each card in turn exchaning the card with another randomly selected card To produce the index of the latter card the random number generator rst produces a randomly selected integer value using by the method nextlnt Since this value could 108 CHAPTER 8 A CASE STUDY SOLITAIRE potentially be negative the math library function abs is called to make it positive The modular division operation is nally used to produce a randomly selected integer value between 0 and 52 A subtle feature to note is that we are here performing a random acc ss to the elements of a Stackl The conventional view of a stack does not allow access to any but the topmost elementt Howeve in the Java library the Stack container is constructed using inheritance from the Vector class Thus any legal operation on a Vector such as the method elementAt can also be applied to a Stack The method select is invoked when the mouse button is used to select the card deckl If the deck is empt it does nothing Otherwise the topmost card is removed from the deck and added to the discard pile Java does not have global variables Where a value is shared between multiple instances of similar classes 1 as the various piles used in our solitaire game an instance variable can be declared staticl A will noted in Chapter 2 one copy of a static variable is created and shared between all instances In our present program static variables will be used to maintain all the various card piles These will be held in an instance of class Solitaire which we will subsequently describe To ac is these values we use a complete quali ed name which includes the name of the class as well as the name of the variable This is shown in the select method in Figure 86 which refers to the variable SolitarediscardPile to access the discard pile 833 The Discard Pile The class Discard Pile Figure 87 is interesting in that it exhibits two very different forms of inheritance The select method overrides or replaces the default behavior provided by class CardPile replacing it with code that when invoked when the mouse is pressed over the card pile chec s to see if the topmost card can be played on any suit pile or alternative r on any tableau pile If the card cannot be played it is kept in the discard pile The method addCard is a different sort of overriding Here the behavior is a re nement of the default behavior in the parent class That is the behavior of the parent class is completely executed and in addition new behavior is added In this case the new behavior ensures that when a card is placed on the discard pile it is always face up After satisfving this condition the code in the parent class is invoked to add the card to the pile by passing the message to the pseudo variable named superl Another form of re nement occurs in the constructors for the various subclasses Each must invoke the constructor for the parent class to guarantee that the parent is properly initialized before the constructor performs its own actions The parent constructor is in voked by the pseudo variable super being used as a function inside the constructor for the child class In Chapter 393 we will have much more to say about the distinction between replacement and re nement in overriding 83 CARD FILESVVVINHERITANCE IN ACTION 109 class DeckPile extends CardPile DeckPile int x int y rst initialize parent superx y then create the new deck rst put them into a local pile for int i 0 i lt 4 i for int j 0 j lt 12 j addCardnew Cardi j then shuf e the cards Random generator new Random for int i 0 i lt 52 i int j Mathabsgeneratornextlnt Z 52 swap the two card values Object temp thePilee1ementAti thePilesetElementAtthePilee1ementAtj i thePilesetElementAttemp j public void selectint tx int ty if isEmpty return SolitarediscardPileaddCardpop Figure 86 The class DeckPiIe 110 CHAPTER 8 A CASE STUDY SOLITAIRE class DiscardPile extends CardPile DiscardPile int x int y super x y public void addCard Card aCard 39f aCardfaceUp aCardflip superaddCardaCard public void select int tx int ty if isEmpty return Card topCard pop for int i 0 i lt 4 i if SolitaresuitPileicanTaketopCard SolitaresuitPileiaddCardtopCard return for int i 0 i lt 7 i if SolitaretableauicanTaketopCard SolitaretableauiaddCardtopCard return nobody can use it put it back on our list addCardtopCard Figure 87 The class DiscardPiIe 84 THE APPLICATION CLASS 111 834 The Tableau Piles The most complex of the subclasses of CardPiIe is that used to hold a tableau or table pile It is shown in Figures 88 and 89 Table piles differ from the generic card pile in the following wa 0 When initialized by the constructor the table pile removes a certain number of cards from the deck placing them in its pile The number of cards so removed is determined by an additional argument to the constructor The topmost card of this pile is then displayed face up 0 A card can be added to the pile method canTa ke only if the pile is empty and the card is a king or if the card is the opposite color from that of the current topmost card and one smaller in rank 0 When a mouse press is tested to determine if it covers this pile method includes only the left right and top bounds are checked the bottom bound is not tested since the pile may be of variable lengt i 0 When the pile is selected the topmost card is ipped if it is face down If it is face up an attempt is made to move the card rst to any available suit pile and then to any available table pile Only if no pile can take the card is it left in place 0 To display the pile each card in the pile is drawn in turn each moving down slightly o ac s the individual elements of the stack an Enumeration is created Enumeration objt are provided by all the containers in the Java libra r39 and allow one to easily loop over the elements in the container 84 The Application Class Figure 8410 shows the entral class for the solitare applicationl in our earlier case studies the control is initially given to the static procedure named main which creates an instance of the application class The constructor for the application creates a window for the application constructing an instance of a nested class SolitareFrame that inherits from the library class Frame After invoking the init method which performs the application initialization the window is given the message show which will cause it to display itself 7e noted earlier that the variables maintaining the different piles which are shared in common between all classes are declared as static data elds in this class These data elds are initialized in the method name 39 39 Arrays in Java are somewhat different from arra 11 most languages Java distinguishes the three activities of arr y declaration ar r39 allocation and assignment to an array lo cation Note that the declaration statements indicate only that the named objects are an array and not that they have any speci c bound One of the rst steps in the initialization v S H 112 CHAPTER 8 A CASE STUDY SOLITAIRE class TablePile extends CardPile TablePile int x int y int c initialize the parent class superx y tlien initialize our pile of cards for int i 0 i lt c i addCardSolitaredeckPilepop ip topmost card face up topflip public boolean canTake Card aCard if isEmpty return aCardrank 12 Card topCard top return aCardcolor topCardcolor ampamp aCardrank topCardrank 1 public boolean includes int tx int ty don t test bottom of card return x lt tx ampamp tx lt x Cardwidth ampamp 3 lt ty public void display Graphics g int localy y for Enumeration e thePileelements ehashMoreElements Card aCard Card enextElement aCarddraw g x localy localy 85 Figure 88 The class TablePile part 14 84 THE APPLICATION CLASS 113 class TablePile extends CardPile public void select int tx int ty if isEmpty return if face down then ip Card topCard top if topCardfaceUp topCardflip return else see if any suit pile can take card topCard pop for int i 0 i lt 4 i if SolitaresuitPileicanTaketopCard SolitaresuitPileiaddCardtopCard return else see if any other table pile can take card for int i 0 i lt 7 1 if SolitaretableauicanTaketopCard SolitaretableauiaddCardtopCard return else put it back on our pile addCardtopCard Figure 89 The class TablePile part 24 111 CHAPTER 8 A CASE STUDY SOLITAIRE public class Solitare static public DeckPile deckPile static public DiscardPile discardPile static public TablePile tableau J static public SuitPile suitPile J static public CardPile allPiles J private Frame window static public void main String J args Solitare world new Solitare public Solitare window new SolitareFrame init windowshow public void init rst allocate the allPiles new CardPileElBJ suitPile new SuitPileE J tableau new TablePile7J then 11 them in allPilesEOJ deckPile new DeckPile335 30 allPiles1J discardPile new DiscardPile268 30 for int i 0 i lt 4 i allPiles2iJ suitPileEiJ new SuitPile15 Cardwidth10 i 30 for int i 0 i lt 7 i allPiles6iJ tableauiJ new TablePile15Cardwidth5i Cardheight85 i1 private class SolitareFrame extends Frame Figure 810 The class Solitaire 85 PLAYING THE POLYM ORPHI C GAME 115 routine is to allocate space for the three ar s the suit piles the tableau and the array aIIPiIes we will discuss shortly The new command allocates space for the arrays but does not assign any values to the array elements The next step is to create the deck pilel Recall that the constructor for this class creates and shu les the entire deck of 52 cards The discard pile is similarly constructe l 4 loop then creates and initializes the four suit piles and a second loop creates and initializes the tableau pilesl Recall that as part of the initialization of the tableau cards are removed from the deck and inserted in the tableau pile The inner class SolitareFra me used to manage the application window is shown in Fig ure 84114 In addition to the cards a button will be placed at the bottom of the window Listeners are created both for mouse events see Chapter 5 and for the button When pressed the button will invoke the button listener method This method will reinitialize the game then repaint the window Similar v ien the mouse listener is invoked in response to a mouse press the collection of card piles will be examined and the appropriate pile will be displayed n 85 Playing the Polymorphic Game Both the mouse listener and the repaint method for the application window make use of the array aIIPie54 This array is used to represent all 13 card pilesl Note that as each pile is created it is also assigned a location in this array as well as in the appropriate static variable We will use this array to illustrate yet another aspect of inheritance The principle of substitutability is used here The array aIIPiIes is declared as an array of CardPiIe but in fact is maintaining a varie y of card pilesl This ar r39 of all piles is used in situations where it is not important to distinguish between various types of card piles for example in the repaint pro edure To repaint the display each different card pile is simply asked to display itself Similarly when the mouse is pressed each pile is queried to see if it contains the given position if so the card is selected Remember of the piles being queried here seven are tableau piles four are foundations and the remaining are the discard pile and the deck Furthermore the actual code executed in response to the invocation of the includes and select routines may be different in each call depending upon the type of pile being manipulated The use of a variable declared as an instance of the parent class holding a value from a subclass is one aspect of polymorphism a topic we will return to in more detail in a subsequent chapter 86 Building a More Complete Game The solitaire game described here is minimal and exceedingly hard to win A more realistic game would include at least a few of the following variations 116 CHAPTER 8 A CASE STUDY SOLITAIRE private class SolitareFrame extends Frame private class RestartButtonListener implements ActionListener public void actionPerformed ActionEvent e init repaint private class MouseKeeper extends MouseAdapter public void mousePressed MouseEvent e int x egetX int y egetY for int i 0 i lt 13 i if allPilesiincludesx y allPilesEiselectx y repaint public SolitareFrameO constructor for Window setSize600 500 setTitlequotSolitaire Gamequot addMouseListener new MouseKeeper Button restartButton new ButtonquotNew Gamequot restartButtonaddActionListenernew RestartButtonListener addquotSouthquot restartButton public void paintGraphics g for int i 0 i lt 13 i allPilesEidisplayg Figure 811 Thc inncr class SolitareFrame 86 BUILDING A EMORE CORIPLETE GARIE 117 o The method select in class TablePiIe would be extended to recognize buildsl That is if the topmost card could not be played the bottommost face up card in the pile should be tested against each tableau pile if it could be played the entire collection of face up cards should be moved Our game halts after one series of moves through the deck An alternative would be that when the user selected the empty deck pile by clicking the mouse in the area covered by the deck pile the discard pile would be reshu sled and copied back into the deck allowing execution to continue Various other alternatives are described in the exe Study Questions 14 What data values are maintained by class Card What behaviors can a card perform That is what methods are implemented by the class Card 2 Explain why the suit and rank data elds are declared as private 3 What is a default constructor What is a copy constructor 44 What is an accessor function What is what advantage of using an ac sor function as opposed to direct access to a data member Why might you want to make ac sor functions into inline functions What factors should you consider in deciding whether to declare a function in an inline fashion 64 What are the 13 different card piles that are used in the solitare game 74 What is a virtual member function Describe the ve virtual functions implemented in class CardPile and overridden in at least one child class 84 How does the use of inheritance reduce the amount of code that would otherwise be necessary to implement the various types of card piles 9 Explain the difference between overriding used for replacrnent and overriding used for re nement Find another example of each in the methods associated with class CardPile and its various subclasses 10 Explain how polymorphism is exhibited in the solitare game applicationl 118 CHAPTER 8 A CASE STUDY SOLITAIRE Exercises 1 N 63 yla The solitaire game has been designed to be as simple as possible A few features are somewhat annoying but can be easily remedied with more coding These include the following a The topmost card of a tableau pile should not be moved to another tableau pile if there is another face up card below it A 3 An entire build should not be moved if the bottommost card is a king and there are no remaining face down cardsl For each describe what procedures need to be changed and give the code for the updated routine The following are common variations of klondike For each describe which portions of the solitaire program need to be altered to incorporate the change a If the user clicks on an empty deck pile the discard pile is moved perhaps with shuffling back to the deck pile Thus the user can traverse the deck pile multiple times Cards can be moved from the suit pile back into the tableau pilel A A n 3 Cards are drawn from the deck three at a time and placed on the discard pile in reverse order As before only the topmost card of the discard pile is available for playing If fewer than three cards remain in the deck pile all the remaining cards as many as that may be are moved to the discard pile In practice this variation is often accompanied by variation 1 permitting multiple passes through the deck A Q The same as variation 3 but any of the three selected cards can be played This requires a slight change to the layout as well as an extensive change to the discard pile class e Any royalty card not simply a king can be moved onto an empty tableau pilel The game thumb and pouch is similar to klondike except that a card may be built on any card of next higher rank of any suit but its own Thus a nine of spades an be played on a ten of clubs but not on a ten of spades This variation greatly improves the chances of winning According to Morehead the chances of winning Klondike are 1 in 30 whereas the chances of winning thumb and pouch are 1 in 44 Describe what portions of the program need to be changed to accommodate this variation The game whitehead is super cially similar to klondike in the sense that it uses the same layout However uses different rules for when card can be played in the tableau 11011 121112A 11 1 0112 3011100012 01 303111210 01 01 30011 11112130111 01 1 0 0110111011 1121 m 01 110210 I I I I 3 I 11110 0111120 0111 30 0112 11111111 0111 111 0131120 1112 31 110110111 011 K1110 11120 11111111 V 1 39S1112011 30 141 12 10 0111101111211 30 141 12 110 1011 11111 1101112110 30 141 12 10 0111110 10 x10 12 1011110 110 p01i121d 011 11120 2101112110 30 0119 12 01111111214010c1 3111121 1111011121110 0110 01111112 1010 9111729 0111 01211 11 31 K1110 11120111121 0111 111 111120 11100123 1011101112 01110 110110111 011 11120 111120 V 12 SH SEISIOHEIXEI Part I Understanding the Ob ject Oriented World View Chapter 1 Ob ject Oriented Thinking This is a book about object oriented programming In particular this is a book that explores the principle ideas of ob ject oriented programming in the context of the Java programming language Object oriented programming has been a hot topic for over a decade and more recently Java has become the commonly perceived embodiment of object oriented ideas This book will help you understand Java It makes no pretensions to being a language reference manual there are many other books that fall into that category But knowing the syntax for a language should not be confused with an understanding of why the language has been developed in the way it has w iv certain things are done the way they are or why Java programs look the way they do This book explores this issue of why Object oriented programming is frequently referred to as a new programming paradigm The word paradigm originally meant example or model For example a paradigm senter e would help you remember how to conjugate a verb in a foreign language More generally a model is an example that helps you understand how the world works For example the Newtonian model of physics explains why apples fall to the ground In computer science a paradigm explains how the elements that go into making a computer program are organized and how they interact with each other For this reason the rst step in understanding Java is appreciating the object oriented world view 11 A Way of Viewing the World To illustrate the major ideas in object oriented programming let us consider how we might go about handling a real world situation and then ask how we could make the computer more closely model the techniques employed Suppose Iwish to send owers to a friend who lives in a city many miles away Let me call my friend Sally Because of the distance there is no possibility of my picking the owers and carrying them to her door in 39 39 sending her the owers is an easy enough task I merely go down to my local orist who 397 a a 0 r1 ii 5 239 13 14 CHAPTER 1 OBJECTORIENTED THINKING Sally 7 Delivery Person Gardeners Flower Arranger Grower ME 7 Flora p Wholesaler Sally s FlOI ISt Figure 11 The community of agents helping me happens to be named Flora tell her the variety and quantit 39 of ow 39s Iwish to send and give her Sall s address and I can be assured the owers will be delivered expediently and automatically 111 Agents and Communities At the risk of belaboring a mint let me em hasize that the mechanism I used to solve rnv a I I V problem was to nd an appropriate agent name V oral and to pass to her a m 5 containing my request It is the responsibility of Flora to satisfy my request There is some methdrrrsome algorithm or set of operationswused by Flora to do this I do not need to know the particular method she will use to satisfy my request indeed often I do not want to know the details This information is usually hidden from my inspection If I investigated however Imight discover that Flora delivers a slightly different message to another orist in my friend s cit 2 T iat orist in turn perhaps has a subordinate who makes the ower arrangement The orist then passes the owers along with yet another message to a delivery person and so on Earlier the orist in Sally s city had obtained her owers from a ower wholesaler who in turn had interactions with the ower growers each of whom had to manage a team of gardeners So our rst observation of object oriented problem solving is that the solution to my problem required the help of many other individuals Figure 11 Without their help my problem could not be easily solved We phrase this in a general fashion as the following An object oriented program is structured as a community of interacting agents called objee s Eac 1 object has a role to play Each object provides a serv performs an action that is used by other members of the community 01121011312111 10110 0112111101111112 1112 01121211 1111112110111 111111 011 1112 112 1210111101 0111 2111111212110111111 011 11 3911101110111 112111 3111111021 1101 1101110111 12 0111211 1011 1112111 011 11110111 11111 01 2110111011 1111021 01 1211111011 11111 1110111103 112112 1 11 391210111101 01111221 0111 01 0211101121011 1111211011 1111 1102111 112111 111011 11101011111 011 111111 12101 c1 01 110 1210111101 0111 311121211211 11111111121 1100111101111 1112 111 1210111101 0111 11121111221 01 2102111 111011122113 1101110111 0111 1011011011 111110111 11111 01 1101101111011 011 111111 2110111011 211 112111 110011110111 011 111111 0111001110 11101012121111221 12 111112 11 11111212110111111 111111 01121 111112 011111112110 10 111011122113 011111 11111 01 031221210111 12 01113 11120 1 3921101110001 11101011111 1111111 1111211 11120 111112 1101110001 0111 110 11101111011011 211 031221210111 0111 01 11110112101 0111021111101110111 0111 211 112111 031221210111 01111011011919111191111 0111 112111 211 111100021 0111 39101110001 110112113121011 011 211 010111 11120 011111000111 12 111 39111021 211 031221210111 0111 110111111 01 1001110 0111021 211 101110001 0111 2031221210111 112111 10119171119991 110112113121011 12 211 010111 031221210111 12 111 112111 211 121111 0111 3921110110111121111 11112110111111 01111 0112 010111 111151 391210111101 0111 311111101101 110112111111 011 111111 112111 21110121 1101190111100 10 1021 12 211 010111 21021120 111011 111 1111120 011111000111 12 11221 111011 111010131111 031221210111 12 211 02111021 11211111 111 39210312113 11121 11211011110111100 111 311111111112130111 10 100112112 11112110111111 1112 021112 211 311111111 1101112111101111 3921101110 1111 1101111111 01121111021 1211111 01 21210113111111111 12 211 2111101101111100 011112211101 10 02111 0111 111 110121 121111 11112110111111 1112 111112 2111101101111100 011112211101 10 11101111101011011 0111 211 311111111112130111 11011101101 1110 10 111211 11112110111111 11V 3921101110 10 21001111021 0111 02111 1011 111112 31111111110110 0111111 12111111 01121 10 011 112111 11111111 2111101111111211301111 0111 111 120111 0111 211 01110010110 01 0111111111 11110111111 12 1111110111105 39210111111111001 11211011110111100 111 0011011011110 0111211101110 1111111 211011111112130111 111112111 111 1101111101112 21011100011 110110 1101101201 111100021 211111 1110111 0111 011 01 112112 11120 01121 10 011 02110 1111011 0111021 111111 01 211 1110110 0111 10 1113110111 121111 0111 1111011011 01 1121121 12 211 010111 11 39311121211211 031221210111 111 11011111111 211 0021 0111 112111 11121111111 001 1112 0111101111111 1011101112 211 010111 391101011011 011 111111 1210111101 0111 110111111 1111 2111120111 112111012 0111 11101111 1011 110011 1210111101 0111 31111111021 1110110 0111 211 11211122311121211211 031221210111 01 11112301 111 111111111 1101171111101 10 0111101111111 11112110111111 0111 1101011 0111211 0111 391210111101 0111 11121111221 01 1101119111 0111021 1111011011 11111 10110001 0111 031221210111 12 01 0211101121011 111 3911011012 1101120111111 0111 1110 1111120 01 11111111121110112101 0111 2111100012 11 031221210111 0111 2111100012 101110001 0111 11 39111021 211 031221210111 0111 111011111 01 1001110 0111 21119019991 0111 391210111101 0111 1110 1111120 01 110110011 211110111 113112 1101112111101111 112110111111112 111112 1111 110111121111100012 211 111112 11011012 1112 10 1210111101 0111 2101100110 031221210111 0111 3911011012 0111 101 0111121110112101 1995110 1112 1110312 1112 01 9109 99m 12 10 11012121111121111211 0111 1111 311111111112130111 11011101101001110 111 110112111111 211 110110V 1130112111111 0112 3 11111012 110111111 1amp1 010111011 0113 51 311111109 IIIOI101I 1301110110 100f110 10 011110111111 111011 1110 01 1210111101 31111112111 1111 101110 110120 1111111 1012101111 1111111111111100 211111 10 2110111110111 112111 0101010111 0021 0111 11110111r 11111 1101101201 111011211111111 2110111011 11111 1111111 211210111101 010111 111121 01 111201 11011111 211210111101 101110 01 111201 1210111101 211111 3912101c1 01 1210111101 11111 1111111 11123011 111121130111 11111 01 11011111021 0111 111 11011112101 111011211111111 112111 1101101201 11112110 0111 513011an pm sa essaw 311 9391 GTHOAX 3H1 DA 113111 10 AVA V 39I39I 16 CHAPTER 1 OBJECTORIENTED THINKING Let us move our disc ission back to the level of computers and programs There the distinction between message passing and procedure calling is that in message passing there is a designated receiver and the interpretationthe selection of a method to execute in response to the messagemmay vary with different receivers Usually the speci c receiver or any given message will not be known until run time so the determination of which method to invoke cannot be made until then Thus we say there is late binding between the message function or procedure name and the code fragment method used to respond to the message This situation is in contrast to the very early compile time or link time binding of name to code fragment in conventional procedure calls 113 Responsibilities A fundamental concept in object oriented programming is to describe behavior in terms of responsibilim Iy request for action indicates only the desired outcome owers for my friend Flora is free to pursue any technique that achieves the desired objective and is not hampered by interference on my part By discussing a problem in terms of responsibilities we increase the level of abstraction This permits greater independence bet a critical factor in solving complex problems The entire collection of responsibilities as ciated with an object is often described by the term protocol A traditional program often operates by acting on data structures for example hang ing elds in an array or record In contrast an object oriented program 39roqu t5 data structures that is objects to perform a service This difference between viewing software in traditional structured terms and viewing it from an object oriented perspective can be summarized by a twist on a well known quote a Ask not what you can do to your data structures but rather ask what your data structures can do for you 114 Classes and Instances Although I have only dealt with Flora a few times I have a rough idea of the behavior I can expect when I go into her shop and present her with my request I am able to make certain assumptions because I have information about orists in general and I expect that Flora being an instance of this category wi t the general pattern We can use the term Florist to represent the category or ol of all orists Let us incorporate these notions into our next principle of object oriented programming All objects are inston 5 of a class The method invoked by an object in response to a message is determined by the class of the receiver All objects of a given class use the same method in response to similar messages 11 A IVAY OF VIEIVING THE WORLD 17 Material Object Animal Shopkeeper Florist Figure 12 The categories surrounding Flora 115 Class HierarchiesInheritance I have more information about Florawnot necessarily because she is a orist but because she is a shopkeeper I know for example that I probably Will be asked for money as part of the transaction and that in return for payment I will be given a receipt These actions are true of grocers stationers and other shopkeepers Since the category Florist is a more specialized form of the category Shopkeeper any knowledge I have of Shopkeepers is also true of Florists and hence of Flora One y to think about how I have organized my knowledge of Flora is in terms of a hierarchy of categories see Figure 12 Flora is a Florist but Florist is a specialized form of Shopkeeperl Furthermore a Shopkeeper is also a Human so I know for example that Flora is probably bipedal A Human is a Mammal therefore they nurse their young and have hair and a Mammal is an Animal therefore it breathes oxygen and an Animal is a Q 18 CHAPTER 1 OBJECTORIENTED THINKING Material Objects Animal Plant Mammal Flo er Dog Human Platypus Car ation Shopkeeper Artist Dentist Florist Potter F lash F lam Elizabeth Kenneth Phyl Sally 5 owers Figure 13 A class hierarchy for various material objects Material Object therefore it has mass and weight Thus quite a lot of knowledge that I have that is applicable to Flora is not directly associated with her or even with her category Florist The principle that knowledge of a more general category is also applicable to a more speci c category is called inheritance We say that the class Florist will inherit attributes of the cla s or category Shopkeeperl There is an alternative graphical technique often used to illustrate this relationship particularly when there are many individuals with differing lineage s This technique shows classes listed in a hierarchical tree like structure with more abstract classt such as Material Object or Animal listed near the top of the tree and more sp c and nally individuals are listed near the bottom Figure 13 shows this class hierarchy for Flora This a 5 11 A WAY OF VIEW VG THE WORLD 19 same hierarc y also includes Elizabeth my dog Flash Phyl the platypus who lives at the zoo and the am sending to my friend Information that Ipossess about Flora because she is an instance of class Human is also applicable to my wife Elizabeth for example Information that I have about her because she is a Mammal is applicable to Flash as well Information about all members of Material Object is equally applicable to Flora and to her owers We capture this in the idea of inheritance D O Q 5 N r gt lt Classes can be organized into a hierarchical lullc m39tancc structure A child class or subclass will inherit attributes from a parcnt class higher in the tree An abstract parcnt class is a class such as Mammal for which there are no direct instances it is used only to create subclasses 116 Method Binding Overriding and Exceptions Phyl the platypus presents a problem for our simple organizing structure I know that mammals give birth to live children and Phyl is certainly a Mammal yet Phyl or rather his mate Phyllis lavs eggs To accommodate thi we need to nd a t thnique to encode carccpmcns to a general rule We do this by decreeing that information contained in a subclass can ovcr39i39ldc information inherited from a parent class Most often implementations of this approach takes the form of a method in a subclass having the same name as a method in the parent class ombined with a rule for how the search for a method to match a speci c message is conducted The search for a method to invoke in response to a given message begins with the class of the receiver If no appropriate method is found the search is conducted in the parcnt class of this class The search continues up the parent cl39 until either a method is found or the parent class chain is exhausted In the former case the method is executed in the latter case an error message is issued If methods with the same name can be found higher in the class hierarchy the method executed is said to m me the inherited behavion J J g 3 Even if the compiler cannot determine which method will be invoked at run time in many object oriented languages such as Java it can determine whether there will be an appropriate method and issue an error message as a compile time error diagno rather than as a run time message That my wife Elizabeth and my orist Flora will respond to my message by different methods is an example of one form of polymorphism We will discuss this important part of object oriented programming in Chapter 12 As explained that I do not and need not know exactly what method Flora will use to honor my message is an example of lVlfavvriatlan hiding 20 CHAPTER 1 OBJECTORIENTED THINKING 117 Summary of ObjectOriented Concepts Alan K considered l 39 some to be the father of object oriented programming identi ed the following characteris ics as fundamental to GOP Kay 1993 1 Everything is an object N Computation is performed by ob jec communicating with each other requesting that ot ier o jec s per orm actions Objec communicate by sending and rt ving mes sage 2 A message is a request for action bundled with whatever arguments may be necessary to complete the task 9 3 Each object has its own memory which consists of other objects H Every object is an instance of a class A class simply represents a grouping of similar objec such as integers or lists C The class is the repository for behavior associated with an object That is all objects that are instances of the same class can perform the same actions 9 Classes are organized into a singly rooted tree structure called the inheritance Iner a rehyV Memory and behavior associated with instances of a class are automatically available to any class associated with a descendant in this tree structure 12 Computation as Simulation The view of rogramming re resented by the exam le of sendirw owers to rnv friend is verv I a a I V I a V V different from the conventional conception of a compute The traditional model describing the behavior of a computer executing a program is a processstate or pigeonhale model In this view the computer is a data manager following some pattern of instructions wandering through memor ullin g values out of various slots memory addres transforming them in some manner and pushing the results back into other slots see Figure 14 By examining the values in the slots we can determine the state of the machine or the results produced by a computation Although this model may be a more or less accurate picture of what takes place inside a computer it does little to help us understand how to solve problems using the computer and it is certainly not the way most people pigeon handlers and postal workers excepted go about solving problems In contrast in the objt ables assignments or any Obth oriented framework we never mention memory addrt ses vari of the conventional programming termsV Instead we speak of messages and responsibility for some action In Dan Ingallsquots memorable phrase Instead of a bit grinding processor plundering data structures have a uni verse of w ll behaved objects that courteously ask each other to carry out their various desires Ingalls 1981 1 2 COMPUTATION AS SIMULATION 21 Figure 144 Visualization of imperative programming Another author has described object oriented programming as animist creating a host of helpers that form a community and assist the programmer in the solution of a problem Actor 1987 This view of programming as c eating a universe is in many wa similar to a s yle of computer simulation called discrete event driven simulation In brief in a discrete event driven simulation the user creates computer models of the various elements of the simulation describes how they will interact with one another and sets them moving This is almost identical to the average ob ject oriented program in which the user describes what the various entities in the universe for the program are and how they will interact with one another and nally ts them in motion Thus in object oriented programming we have the view that computation is simulation Kay 1977 4 121 The Power of Metaphor An easily overlooked bene t to the use of ob ject oriented techniques is the pow 39of metaphor When programmers think about problems in terms of behaviors and responsibilities of ob they bring with them a wealth of intuition ideas and understanding from their ev erydav experience When envisioned as pigeon holes mailboxes or slots containing values ther is little in the programmer s background to provide insight into how problems should be structuredl lthough anthropomorphic des riptions such as the quote by Ingalls may strike some people as odd in fact they are a re ection of the great expo tive power of metaphor Journalists make use of metaphor every day as in the following description of ob ject oriented programming from Newsweek 22 CHAPTER 1 OBJECTORIENTED THINKING Unlike the usual programming method 39iting software one line at a tlHlC39quot NeXT s object oriented s 39stem offers larger building blocks that developers can quickly assemble the way a kid builds faces on Mr Potato Head Possibly it is this power of metaphor more than any other feature that is responsible for the frequent observation that it is often easier to teach obj d programming concepts to computer novices than to computer professionals ovice users quickly adapt the metaphors with which they are already comfortable from their everyday life whereas seasoned computer professionals are blinded by an adherence to more traditional ways of viewing computation As you start to examine the Java programs presented in the book as well as creating your own Java programs you may nd it useful to envision the process of programming as similar to the task of training a universe of agents to interact smoothly with each other each providing a certain small and well de ned service to the others each contributing to the effective execution of the whole Think about how you have organized communities of individuals such as a club or committee Each member of the group is given certain responsibilities and the achivement of the goals for the organization depend upon each member ful lling their role x O N a d H a 13 Chapter Summary 0 Object oriented programming is not simply a few new features added to programming languages Rather it is a new way of thinking about the process of decomposing problems and developing programming solutions 0 Object oriented programming views a program as a collection of loosely connected agents termed objects Each object is responsible for speci c tasks It is by the interaction of objects that computation proceeds In a certain sense therefore pro gramming is nothing more or less than the simulation of a model universe An object is an enczwsulation of state data values and behavior operations Thus an object is in many ways similar to a module or an abstract data typo The behavior of objects is dictated by the object class Every object is an instance of some class All instances of the same class will behave in a similar fashion that is invoke the same method in response to a similar request 0 An object will exhibit its behavior by invoking a method similar to executing a procedure in response to a messagel The interpretation of the message that is the speci c method used is decided by the object and may differ from one class of objects to another F urther Reading 23 o Obje s and classes extend the concept of abstract data types by adding the notion of inheritance Classes can be organized into a hierarchical inheritance tree Data and behavior associated with classes higher in the tree can also be accessed and used by classes lower in the tree Such classes are said to inherit their behavior from the parent classes 0 Designing an object oriented program is like organizing a community of individuals Each member of the community is given certain responsibilities The achivement of the goals for the community as a whole come about through the work of each member and the interactions of members with each other 0 By reducing the interdependency among software components object oriented pro gramming permits the development of reusable software systems Such components can be created and tested as independent units in isolation from other portions of a software application 0 Reusable software components permit the programmer to deal with problems on a higher level of abstraction We can de ne and manipulate objects simply in terms of the messages they understand and a description of the tasks they perform ignoring implementation details Further Reading I said at the beginning of the chapter that this is not a reference manual The reference manual written by the developers of the language is Gosling 96 But perhaps even more useful for most programmers is the annotated lCSL iption of the Java class libra r39 pre sented by Chan 96 Information on the internal workings of the Java em is presented by Lindholm 97 I noted earlier that many consider Alan Kay to be the father of object oriented pro gramming Like most simple assertions this one is only somewhat supportable Kay himself Kay 1993 traces much of the in uence on his development of Smalltalk to the earlier computer programming language Simula developed in Scandinavia in the early 1960s Dahl 1966 A more accurate history would be that most of the principles of object oriented programming were fully worked out by the developers of Simula but that these would have been largely ignored by the profession had they not been rediscovered by Kay in the creation of the Smalltalk programming language I will discuss the history of GOP in more detail in the next chapter Like most terms that have found their way into the popular jargon object oriented is used more often than it is de ned Thus the question What is object oriented programming is surprisingly difficult to answer Bjarne Stroustrup has quipped that many arguments appear to boil down to the following syllogism o X is good 24 CHAPTER 1 OBJECTORIENTED THINKING o Object oriented is good o Ergo X is object oriented Stroustrup 1988 Roger King argued Kim 1989 that his cat is object oriented After all a cat exhibits char acteristic behavior responds to messages is heir to a long tradition of inherited responses and manages its own quite independent internal state Many authors have tried to provide a pre de iption of the properties a program ming language must possess to be called objc oriented I my e have written an earlier book Budd 97 that tries to explain ob ject oriented conce ts in a language indepent fash ion See also for example the analv by Josephine callef Micallef 1988 or Peter Wegner Wegner 19864 Wegner distinguishes objectbased languages which support only abstraction such as Ada from objectoriented languages which must also support inheri tance Other authorsmnotably Brad Cox Cox 1990rde ne the term much more broadly To Cox object oriented programming represents the objective of programming by assembling solutions from collections of off the shelf subcomponents rather than any particular tech nology we may use to achieve this objective Rather than drawing lines that are c ive we should embrace any and all means that show promise in leading to a new software Industrial Revolution Cox s book on OOP Cox 1986 although written e39 in the development of o jec oriented programming and now somewhat dated in details is nevertheless one of the most readable manifestos of the objec oriented movement Study Questions 1 What is the original meaning of the word paradigm 24 How do objects interact with each other 34 How are messages different from procedure calls 4 What is the name applied to lth ribe an algorithm an object uses to respond to a request Why does the object oriented approach naturally imply a high degree of information hiding 64 What is a class How are classes linked to behavior 74 What is a class inheritance hierarchy How is it linked to classes and behavior 84 What does it mean for one method to override another method from a parent cl 9 What are the basic elements of the process state model of computation F urther Reading 104 How does the object oriented model of computation differ from the proc mot e T 114 In what way is a object oriented program like a simulation Exercises 1 In an object oriented inheritance hierarchy each level is a more specialized form of the preceding level Give an example of a hierarchy found in eve r r life that has this property Some types of hierarc found in everyday life are not inheritance hierarchies Give an example of a hierarcl y that is not an inheritance hierarcl 39 24 Look up the de nition of paradigm in at least three dictionaries Relate these de ni tions to computer programming languages 34 Take a real world problem such as the task of sending owers described earlier and describe its solution in terms of agents objects and responsibilities 44 Consider an object in the real world such as a pet animal Describe some of the classes or categories to which the object belongs Can you organize these categories into an inheritance hierarchy What knowledge concerning the object is represented in each categoryquot If you are familiar with two or more distinct computer programming languages give an example of a problem showing how one language would direct the programmer to one type of solution and a different language would encourage an alternative solution 6 Argue either for or against the position that computing is basically simulation You may want to read the article by Alan Kay in Scicnti c Amci ican Kay 1977 4


Buy Material

Are you sure you want to buy this material for

25 Karma

Buy Material

BOOM! Enjoy Your Free Notes!

We've added these Notes to your profile, click here to view them now.


You're already Subscribed!

Looks like you've already subscribed to StudySoup, you won't need to purchase another subscription to get this material. To access this material simply click 'View Full Document'

Why people love StudySoup

Bentley McCaw University of Florida

"I was shooting for a perfect 4.0 GPA this semester. Having StudySoup as a study aid was critical to helping me achieve my goal...and I nailed it!"

Kyle Maynard Purdue

"When you're taking detailed notes and trying to help everyone else out in the class, it really helps you learn and understand the I made $280 on my first study guide!"

Steve Martinelli UC Los Angeles

"There's no way I would have passed my Organic Chemistry class this semester without the notes and study guides I got from StudySoup."


"Their 'Elite Notetakers' are making over $1,200/month in sales by creating high quality content that helps their classmates in a time of need."

Become an Elite Notetaker and start selling your notes online!

Refund Policy


All subscriptions to StudySoup are paid in full at the time of subscribing. To change your credit card information or to cancel your subscription, go to "Edit Settings". All credit card information will be available there. If you should decide to cancel your subscription, it will continue to be valid until the next payment period, as all payments for the current period were made in advance. For special circumstances, please email


StudySoup has more than 1 million course-specific study resources to help students study smarter. If you’re having trouble finding what you’re looking for, our customer support team can help you find what you need! Feel free to contact them here:

Recurring Subscriptions: If you have canceled your recurring subscription on the day of renewal and have not downloaded any documents, you may request a refund by submitting an email to

Satisfaction Guarantee: If you’re not satisfied with your subscription, you can contact us for further help. Contact must be made within 3 business days of your subscription purchase and your refund request will be subject for review.

Please Note: Refunds can never be provided more than 30 days after the initial purchase date regardless of your activity on the site.