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

Adv. Object

by: Dorothy Bahringer DVM

Adv. Object CS 3331

Dorothy Bahringer DVM
GPA 3.85


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 50 page Class Notes was uploaded by Dorothy Bahringer DVM on Thursday October 29, 2015. The Class Notes belongs to CS 3331 at University of Texas at El Paso taught by Staff in Fall. Since its upload, it has received 7 views. For similar materials see /class/231293/cs-3331-university-of-texas-at-el-paso in ComputerScienence at University of Texas at El Paso.

Similar to CS 3331 at UTEP

Popular in ComputerScienence


Reviews for Adv. 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/29/15
11 42009 Question Class Design public class StudentEudyl r private ArrayLlst students V publlcvuld addAllArrayLlst students M V cs 3331 pu ll class StudentEudyZ private LlS L student W V publlcvuld addAllLlst students M V Design Guidelines Canonical Form of Classes G1Avoid public elds 62 Make public interfaces complete G3 Separate interface from implementation E g vvlwatvvlll be printed W LinkEdLlsu pulnts addnevv Pulnt EL 2n lf pulnts cuntalnsnevv Pulnt EL 2mm System but println Fuundl Else System but println l Nut fuundl Canonical Form Cont Equality Identity equality vs value quality s e uals implies equals Canonical forms of public classes 39 String representation No argument constructor Pulntpl nevv Pulnt EI Z F39Ellrlt in SW Pulnt EL zu Oblec t equal39t l F39ulntp37pl ls pl p2 7 Cloning ls pl Equalsp2 7 r r Serialization pa 7 5 pl ls pl Equalsp3 7 Equality Cont Default implementation of equals method Inherited from the class Object Test for object identi Can be overridden by subclasses The hashCode Method Purpose Returns the hash code of an object Used by hashtabIebased collection classes eg HashMap HashSet Contract for hashCode xequalsy 2 xhashCode yhashCode Computing hash code for elds boolearl flelds r7 El l byte Chan SHOTL and lrltflelds 7 lht r lorlgflelds 7 lntfquotfgtgtgt32 floatflel s 7 FluatfluatTulrltElltsf doubleflelds 7 Duuble duubleTuLungElltsf and then in mi References 7 lf hull then u ur same flxed value 7 Recurslve Equals 2 recurslve hash uh helus Dr 7 Hashu arlDrllEalrEprESErltatiDrl 11 42009 Contract of Equality Equivalence relation Re ec ivex equalsx Symmetric xequalsy yequalsx Transitive xequalsy yequalsz gt qualsz Consistency xequalsy consistently returns true or false Nonnullit xequalsnull always returns false De ning hashCode Methods General scheme Compute hash code for each significant field Combine hash code of all signi cant fields publlc hr hashCode l hr result 0 accumulatlve hash code hr h lhash code fora le ltltfureach hel cumpule and cumulhe lhe hash Cudegtgt return resull How to Combine Hash Code Bitwiseor result result ltlt n h where n is an arbitrary integer constant g Addition result resultquot p h where p is a prime number eg 37 How do you manage the complexity Chat Room Application Communications It s very complex Connecting in Java High level of abstraction Support in the class libraries Uses TCPIP Three parts Connecting Sending Receiving 11 42009 Communications Hellu message Break message into Recombine packets smaii packets into message I Packets I Packets Transmit individual Receive individual packet packet it It its Approach Prutucul Stack Il Ethernet WASCATS Connecting in Java Use a Port and an IP address to establish a socket connection TCP port 16 bit number that identi es a speci c ogram 065535 0 1023 are reserved FTP art 20 H39I39I39PS443 H39I39I39P 80 11 42009 Connecting in Java What is the output from this program Socket mySocket new Socket 127 001quot 5000 InputStream Reader stream new InputStream Reader MySocketgetnputStream BufferedReader reader new BufferedReaderstream String msg readerreadLine How to read and write Summary A Socket is a connection between two Client2java appllcatlons A client must know the IP address and TCP port 39 MyserVerzJaVa number of the server A client connects to a server by making a Socket new Socket ltlPgt ltportgt Both input and output streams can be obtained from the Socket Use print or println and readLine Servers use a ServerSocket that waits for client requests on a po It accepts the request and makes a Socket What is the output from this program conne Question Question How many clients can a MyServer or When does the client get messages from MyServer2 handle the servei Options Pros and cons Program Execution Eetph asg e M Emmy os lO Buffers WSWquot HEW Process Context Questions Where do the local variables live How do you know where to return to when a procedure exits 11 42009 Threads Think about the following pseudo code procedureA var x var y local varz Procedure B var u local var w call Au w Main read r1yreadv2 call Bv1 v2 Consider the following int fibbn intv1 v2 v1 bbn1 v2 bbn2 1 2 3 4 5 else 6 7 8 return v1 v2 9 Compute fibb4 Return address N push the return pe an the stack push 4 un stae n sh pu yr empty an the stack yr pu empty an the stack V2 Xecute hne a npp a h 3 an ck n Return tn the a ush hne a h stack 3 p y empty pn stack push yz empty pn stack W REM VE UE execute hne E npp 2 PMquot We npp2 sh yr Return tn the a push yz execute the 4 Actrvatrun pup VZ pr vzpup n W Reeprd pup return address W rprnppa assrgn y epntmue Wrth hne 7 Multitasking Program Execution Memdry I REG Fmgrarn Heap Program Heap nterface must haye39a you run methpd puphe erass MyRunnapre rmprements Runnapre pnyate mt yaruey puphe yend run or rpr rntr El rlt1EEEE r rmdrum u S System put pnntrn Process yarue t at r W 5 WP puphe MyRunnapre rntr yarue h Set the rns tance yanaprerpr new MyRunnapres puphe 51am yend mam Strrnglj argst rprmt em lt3 w new v v Thread myThread new Thread rrryThread starto threa Create three rnstanees and run them system put pnntrn Mam rs dune 11 42009 Show the stack afterthe return at line 8 in bb3 Multithreaded Program Execution Memdry F39C REG I Program Heap What is the output ofthis program To launch a thread Make a Runnable object the job Runnable threadJob new MyRunnable MyRunnable has a public void run method Make a thread object the worker Thread myThread new Thread threadJob Start the thread myThreadstart Sleep method forces block public Vuid run or terihti ti iltiuuuti it niEIEI W a system But println F39rucess value i at l W Thread sieepm catch lnterruptEdEXcEptiun em ex printStackTrac l 11 42009 Threads have 4 states New Runnable Running Blocked Data Race One instance of the runnable job Two threads This gives each thread access to the same data on the heap The data on the stack is still separate What s the output synchronized private synchronized void makeWithdraW iht m Strin s Thread currentThreado getNameO it acct getBalance gt m ystern out prihtih Thread s tries to Withdraw H acct Wit raWUi ys em out prihtih Thread s Withdraw complete else System out prihtih Sorry Thread s cahtwthdraw hi i 11 42009 synchronized Question Only one thread can execute this code at How do you test a program to ensure it a time doesn t have a race condition Makes the test and the action atomic that is undividable What happens Summary static Threadsee forces athread to leave the Class A public void synchronize fA g State P0 Class B pu bllC VOld synchronize fB whenbla tlhrtealljd Wake1 up it goestbalckfonhthe A a new B b new Iiestli gogsyou ave no con F0 0 W ere setName lets you name a thread thread 1 am mo 39 lynzgggnggsggrgg thesamewled thread 2 bfB afA synchronized can control access to a method An thread tryin to enter synchronized code while anothert read is there becomes blocked Identify the problem in the Singleton design pattern public class MyClass private static MyClass uniquelnstance private MyClass private static MyClass getlnstance if uniquelnstance null uniquelnstance new MyClass Singleton Design Pattern Revisited return uniquelnstance 11 42009 Two Programming Languages Words Overloading Inheritance in Java Overriding CS 3331 Overloading of Methods and Constructors Why use overloading ubllcclass Pulnt publl Pulnto m V publl Pulntmntx lnt V publl double dls taneF ulnt utherHF V publl double dls tanceUnIX lnthF V publl double dls tanEEOlF V Why use overloading When to Overload Cont lass nngt publl Stnng substnngnnt r rntm base method return substnng from lndex r ml el l publl Stnng substnngnnt or pruvlde default argument return substnngtr lengtnor publl elass Stnngaunert publl StnngEluffer append Stnng str m V j 11 42009 How does Java figure out which Overloadin method to use 9 new StringBuffer sb append Puinlo iril i Puinlo 2 Peinmniwiniy e ininni 3 duubiedistancePuinlulhei dislancePuinl A eeuieieeisianeenniwini y eisianeenninni dislance m anee 5 duubie PuinlpiZHEWPuinlO Whichcunsliuclui7 Peini p2 new Peinimu 2n p2 distancewi iwnien melhud7 p2 distancea p2 distanceo Overriding Methods Overriding Methods Cont Def Overriding publicciassTi publicvuid mm i public eiass 5 extends Tt Consequences puhiicvuidmoi Tt new T s s new 5 moi iriVEIkE er iassT s m invuke rn er eiass s Implementation of Dynamic 9 What value is returned Binding Storage structure of instance variables eiass Student ubiii int maXCrEdits return 15 p m Dynamic bindings of messages to methods eiass Graduatestudent Extends StudEnH public int maXCrEditsO return i1 Student 5 s gEtM aXCrEditsO wnien maXCrEdits method Dynamic Binding Cont class Penntt private l tX t pubne Purnmnt gtlt rnt y thrsx gtlt thrsy y pubne rnt getgtlt return x pubne rnt gEtYO t return yr class CuluredF umt Extends Penntt private Culur ee err pubne CuluredF mntUnt X My Culur en Ergtltt v culur e pubne Culur gEtCulurO t return ulur Overriding Methods Cont Example class Studentt preteeteu Stnng description Stueent x pubne Stnng getDesenptrenm return descriptlun class Undergraduate Extends Studentt preteeteu Stnng description Unuergrauuate x new Studento gEtDecrrptruml HWhatvalue rs returneu7 newUndergraduateO gEtDEscrrptmml NWhaLvaluE7 Q Huvvtu rerertu hidden elds 11 42009 Dynamic Binding Cont CuluredPumlp new CuluredPuml mzn purer RED p gelCulurO r1 EE XOt omeet class Puml class Culuredpuml lass CulurR ED Hiding Fields and Class M eth ods Def Hiding Hiding vs overriding Statically resolved bound at compiletime vs dynamically dispatched at runtime Another Example eiass Pbihtt pubiie String descriptiun Pbiht x eiass CF39EIirit Extends Pbihtt pubiie String descriptiun CF EIirit CF39EIirit ei new crvbihto F39Elirit e2 ei system out prihtih ei descriptibh system out prihtih e2 descriptibh Constructors of Subclasses Can invoke a constructor of the direct superclass super must be the first statement Ifthe super constructor call is missing by default the noarg super is invoked implicitly Can also invoke another constructor ofthe same class this must be the rst statement Example of super Calls pubiie eiass CDiDrEdF Dint Extends F39Elirit private Cuiur ebiur pubiie cbibreupbihttihtx ihty Cuiur epier this X Xi this y y this ebibr ebibr pubiie cbibreupbihttihtx inty thistx y cbibrELAcm pbihtWith defauitvaiue pubiie CDiDrEdF Dint uiur u ur BLACK vvhatvviii be the values ufgtlt and w 11 42009 Inheritance Inheritance models the isa relationship If class S extends class T then all objects of S can actlike an object of T In Java only single inheritance is allowed among classes All public and protected members of a superclass are accessible in the subclasses Aii protected members are also accessible Within the package Example of this Calls public class Polnl t private int x y public POlnt1nt x int y i thlsy y i public Polnt i default constructor thlsx F thlsy 0 i Default Constructor pubiie CiassNamE supero Q What wuuiu be the use uf default euhstruqur Testing in General Purpose Unit Testing 39 Fihfses What Is Unit Testing Why Unit Testing Testing is 2 A unit is 2 Unit testing is 2 How to Do Unit Testing Coupling Bottom up construction Coupling the degree to which some Starts with classes that don t depend on thers component interacts with other components Continue testing building on already tested classes Benefits Avoid having to write test stubs When testing a module rely only on tested modules Question How does low coupling help testing How does high coupling hurt it Conventional Testing A class tn test the class lMath publl class lMthTestNuJUnltl rquot Runs the tests publl stall V ld malnStrlng args l prlntTestResultm prlyate statlc V ld prlntTestResulmm arg l System crutprlrl lsqn arg w gt l System nut pnmanMath lsqru l 39 Solution Automatic verification by testing program Program to Test publlc rlnal class lMathl N Returnsarl lrlteger approxlmatlon to the square root or x publlc Statlc rm lsqrmm m uess Whlle guess r guess lt m guess return guess l Conventional Test Output wwmmmgg g a De 9 ll rr rr V o What does this say about the code Is it right What s the problem with this kind of test output Some Terminology Definition A test data or case for a method M is a pair of o args where is not null and M can be sent to 0 args is a tuple ofargumems that can be passed to M A test data 0 args for M succeeds iffoMargs behaves as expected A test data 0 args for M fails iff it does not behave as expected Question Why should 0 not be null If M has a ug hat is revealed by a test data does that test data for M succeed or fail Design Patterns ModelView Separation Motivation Suppose we support both the command line and the GUI interfaces ModelView Context ContextProblem It is desirab1e to decouple domain mode1 objects from windows views to support increased reuse of domain objects and minimizethe impact of changes in the interface upon domain objects Motivation Suppose you have a system that needs to run on a variety of devices 7 Maybe a cell phone and aPDA 7 Maybe Windows and with a command line Think about the current programming assignment ModelView Separation Pattern Model The domain layer of objects objects that contain data and operations View The presentation layer of objects windows applets reports ModelView Context ContextProblem It is desirab1e to decouple domain mode1 objects from windows views to support increased reuse of domain objects and minimizethe impact of changes in the interface upon domain o jec s Sohition De ne the domain mode1 c1asses so that they do not have direct coupling or visibi1ity to the window view c1asses and so that app1ication data and functionality is maintained in omain c1asses not window c1asses ModelView View Medel Problem View displayMessage Model ModelView Separation Pattern I Problem Domain objects need to communicate with windows to cause a real time ongoing display update as the state of information in the domain object changes Monitoring applications Simulation applications ModelView Separation Motivation Motivation I Focus more on the domain processes rather than on com uter interfaces I Allow separate development of the model and user interface layers I Minimize the impact of changes in the interface upon the domain layer I Allow new views to be easily connected to an existing domain layer ModelView Separation Pattern View query Model ModelView Separation Pattern With Indirect Visibility NamedPublishSubscribePattem ContextProblem A change in state an event occurs within aPublisher ofthe event and other objects are dependant on or in erested in this event Subscribers to the event However the Publisher should not have direct knowledge b s ofits subscn er 11 42009 Question What is the one thing in software design and development that remains constant 00 Fundamentals Where does it come from What changes Principle 1 Encapsulate Change Recall this question Find What varies or What will vary and WW 5 Deue mWW encaPSUIate 39t public class StudentBody1 t prlvate ArrayLlSt students t V public Vold addAllArrayLlst studentsHF V l public class StudentBodyZl prlvate LlSt students public Vold addAllLlst students l 11 42009 What does a List need to What does a client need to support know about List Principle 2 Code to an interface rather than an implementation COheslon A cohesive class does one thing and one thing only The customer class keeps customer data It doesn t try to compute a bill The board class keeps track ofthe locations of pieces it doesn t try to determine legal moves Princi le 3 Sin le res onsibili p g p ty Finding misplaced methods principle Does The ltclassgt ltmethodgt itself make Every object in your system should have a sense single responsibility and all the object s services should be focused on carrying out that responsibility Example Suppose we are programming a checkers game Comments Principle 4 The openclosed principle Classes should be open for extension but closed for modification Pieee 11 42009 3 different solutions Another solution Two methods for bank program publicfluat getElal DataEla e List Ld searen Aeeeunts x in eeeunt a L benaeti it anull return Vi my eise L searchf return R surn l J ClD id AeetNurn aet ankdata publicfluatwithdraw ClD ld AcctNum act neat amuunt neat balance El EL DataElase u upenf bankdata List Ld searen Aeeeunts in A euntatrnern it anull return else balance R surno l a auuTransaetiu Witnuraw x arneunt return arnuurit else return I L D it arneunt s balance n 11 42009 Fix the code public Account gciAcct ClD ld AcctNum an DataElase c upenf bankdata List Ld Search Acccums x id Account a L membe am return a public float getBal ClD ld AcctNum act Account a getAcct ld act riu i R a searcmwi return R sumo Back to Checkers Suppose we want to allow players to play either of two games Checkers as we know it Principle 5 Don t Repeat Yourself DRY publicfluat Withdraw ClD ld AcmNum act float amuunt float balance a ti Account a gelAcctUd an M Avoid duplicate code by abstracting out raiser things that are common and placing them List R a searchf baiam mo In a single location i if amount lt balanc a addTransactiun return amuuntr ci l Withdraw amount 2 return u EL l 3D Checkers Board Width height irit Content Obiem ocnicnmnr int ubicct remuveCuntent inc int 3D checkers net blEEtllnt inn Principle 6 Substitution Problems What about this code principle Subtypes must be substitutable for base types Board b new 3DBoard Objectx getObject4 5 ObjectOriented Modeling Using UML Dynamic Models CS 3331 Use case diagram Describes the externally observable behavior of system functions usually to define system requirements Describes interactions between the system and external entities Elements of Use Case Diagram Actor Use case Relationship 11 42009 Dynamic Behavior What happens when the program runs How do states of objects change How do objects interact with each other How is data transformed Example Goldmine sveem haundHV o 1 Re iser aday e i d Student c heck Grades ltltincludegtgt A wudde u ser Example Goldmine Cont 7 Wildme User a er Gem g ltltl dudegtgt l extend FBEMW Enter Grades Use Case Scenarios 1 Yhesvsem carries out validate User 2 Yhesvsem Fromm mum vearand semester Sequence diagram Depicts object interaction by highlighting the time ordering of method invocations Describes a sequence of method calls among objects Example Cont Interaction Diagrams 4 types Sequence Diagrams Communication Diagrams Interaction Overview Diagram Timing Diagram Example 11 42009 de laceOrder objectf mum l m l control 7 i T ea l ti Urxmetsage l l l l Sequence Diagram de laceOrder CustomerWlnduvv Create and Delete de laceOrder CustarnerWlnduvv m Change deleteo State All objects have state State is the collection of values maintained by the object that determine behavior State Specification Entry preconditions for the state Exit Postconditions for the state Do Activity in the state 11 42009 Modeling Dynamic Behavior Statechart diagram Depicts the flow of control using states and transitions Generalization of nite state machines State Time in the life ofa system or object during which it Set of values of properties that affect the behavior of the system or object Transition Relationship between two states indicating that a system or object in the rst state will Perform certain actions and Enter the second state when speci ed event occurs and speci ed condition is satis ed Consists of Source and target states Optional event guard condition and action Lead from one state to another Elements of Statechart Simple Phone Example 11 42009 Statechart Diagram Graph representing nite state machine Network of states and transitions Good for modeling reactive systems Definition Event An occurrence of a stimulus that can trigger a state transition Instantaneous no duration Another Example reeevery sueeess recuveryfailure anomaly temperature reeevery failure reeevery sueeess Refacto ri n g from Martin Fowler Refactoring Improving the Design of Existing Code Addison Wesley 1999 Why Usually good design first then code second Example Program calculates and prints a statement of a customer s charges to a video store We know what movies and how long the customer had them children s and new release Program computes a renter s frequent renter points which vary depending on whether the film is a new release There are three kinds of movies regular s 11 42009 Refactoring The process of changing a software system in such a way that it does not alter the external behavior of the code yet improves its internal structure Refactoring is the reverse process Take bad design Rework it into a good design iFicim bunk Rciaciciing by Maiiiii chlci public class Mmicl public siaiic libel im CHlLDR ENS 2 public siaiic libel im NEWj ELEASE l public siaiic libel im REGULAR n pilya E Stilngitltle pilya E lntipilEECDdE public MuylESilng iiilc im leEECDdE iiilcqiilc piiccccuc piiccccuc public im gElPYlEECDdE l iciuin piicccciuc publlcvuld SE PYlEECDdEUM aign piicccciuc 7 avg l public suing g2lTlll20 vetumitltlE pubii ciass Rentait private MDViE imuviE private irit idaysRented pubii RentaiWuvie muvie int daysRentem muvie r rn 7 a mist uaysRenteu daysRented pubii int getDaysRented return idaysRented pubii Muvie gEtMuviE return imuviE Pubiicstvmvsimemem autummumu Mm ueni e e a em 5 eiemeMSO mam vetNameO n Manama mmawantsox aauuammum u am mm mm Wigwam Murecude here raaammm mum sum WW varmcuan germanium c aumuamjzuasz exeMmAeEHiLDRENS namquamm pm Vvequeni emewmns um hams m mu div quotam ram 1 am vamth veWHceEadlt mauamnamrrm nva vuies m ins mm 7 mmauwanarm I swmuamumgmum m msmwau iesuh mama StnnvvaiueDKMaiAmauM n vduvnisuh Draw UML Sequence diagram of statement Mai Mme NEvljEL SE 4am manaan gt1 StunvvaiueDKhequen ReMeWmMS Vvequem Ma pm 11 42009 import java utii Enumeration import java utii Vector pubiic ciass Customert private Stnng Jame private VectorltRentaigt Jentais new VectorltRentaigt pubiic Customer8tring nameH Jame name pubiic void addRentaiRentai arg Jentais addEiemenuarg pubiic stnng getName return iname Draw UML Class diagram of this Impressions of the code 11 42009 Death Taxes and Changes Develop a plan to x the code Advice Whenevera feature needs to be added and adding the feature is hard because of the structure of the code refactor to make adding easier then add the feature Question Refactoring Step 1 When you are done refactoring how do you know you haven t broken the code Jun public class CustumErTest Extends Testbaset RELEASE g Arneunt eweg is 23 mn You earneg 4 treguent renter pulrits String staternent eusternert staternent assertEguaisexpeeteg staternent l Approach Extract cohesive methods that can be mu tg stung stateni tutot daubletmalAmaunt u nttregertneuterpgnts u Euguergttgu rentals rertaisgeuentso stuug resgrt Rental neggrg tgr getNariiEU Wmle rentals uasugresieuentso t daublethisAmaum u n ntai eagu Rental rentals uextsieuento tutsAuggnt auggutrgrteagu iragg neggeut renter Paints neggemnerterpgntsu iragg harms gr 3 tvw day newrelea rental utteagu getrugueo getvugecggeo Mgue NEWJELEASE as eagu getDavsRemedO gt1 neggeutnerterpgntsu r angre rthisremal result 1 eagu getrugueo getnteo 1 stung valueO39 hisAmaum tmalAmaunto tutsAuggnt gt iragg tggter uues ream Amaum Wed is n stung valueo39 malAmaum ream Vau eaueg stung valueomrequent enterl aims neggeut renter paints retgruresgn g tGuriE Witn tne anmt Eri 11 42009 First target statement Why Extract Method ou have a code fragment that can be grouped together rn the fragment into a method with a name explaining the purpose Mechanics Create a new method Copy extracted code from source to target Find variables local to source method but not local to extracted code Make them parameters to new method Checkforlocal variables modi ed in extracted code If there is more than one you may need to refactor before extracting he method Replace extracted code with a call to he target method Compile and test New Metneg private int amuuritFur Rental Each int thisArnuurit D svvitc eaen getMuvieO getF riceCudE Movie REGULAR thisArnuurit t 2 ifeach getDaysRentedo gt 2 thisAmuurit t eaen getDaysRented r 2 t t 5 break ease Movie NEW ELEASE isArnuurit t eaen getDaysRentedO 3 rea ease Movie CHlLDRENS t r ruggnt t t 5 ifeach getDaysRentedo gt a rnegnt t eaen getDaysRented r a t t 5 break l return thisAmuurit l Advice Refactor in small steps and test Ifyou make a mistake it s easierto find private double arhouhtFor Rehtai each iht thisArhouht 0 switch each getMovie getPriceCode EGULAR thisArhourit 2 it each getDavsRehted gt 2 0 mount each getDavsRentedo e 2 t i 5 break case Movie NEvvjeEtEAsE hiSArnourit each getDavsRentedo 3 rea i case Movie CH LDRENS thisArnourit i 5 it each getDavsRentedo gt 3 thiSArnourit each getDavsRentedo e 3 t i 5 break returh HlSAmOUNL l Run the tests gtiavaecp iunitiar CustomerTest Time 0 03 0ilt 7 tests 11 42009 Next step amountFor Some ofthe names aren t very descriptive Rename Variable private double amountFor Rental aRental ht result 0 switch aRerital getlvlovieo getpriceCodei u G LAP result 2 aRerital getDavsRentedo gt 2 sult aRental getDavsRentedo e 2 t i 5 break case Movie NEvvjeEtEASE result aRental getDavsRentedo 3 rea i Case Movie CH LDRENS result aRental getDavsRentedo gt 3 sult aRental getDavsRentedo e 3 t i 5 break Advice Any fool can write code a computer can understand Good programmers write code that humans can understand 1 Next step amountFor Where does it get its information from Rental duuble getCharge or int result r switchgetM vie getF riceCude case MEIVlE REGULAR result Z ifgetDaysRented gt 2 result getDaysRentedO e 2 r 1 5 break case Movie NEW ELEASE resut getDaysRentedO 3 break case Movie CHlLDRENS result 1 5 ifgetDaysRented gt a result getDaysRentedO e 3 f 1 5 break 1 return result publicSlring siaierhehim duublelulalAmuunl n Pcrhisn numeraliun rentalSZJEMals eiemehiso String resuii Rental Recurdlur gelNam20 h While rehiais hasMcreEiemehisoi Rental each Rental rehiais hehEiemehio Mace frequent rehier puinls recuehihehierpcrhiw Mace hchusicra WEI day newrelease rehiai 11each gelMuvieO gelPriEECude Muvie NEWJELEASE m each gelDaysR emedO gt1 frequean enlerPuinlwt shuw figures luv ihrs reh w 1ai resuii e each gelMuvieO lulalArnuuan each gelCharg add iuuier irhes resuii K Amuunl awed is smhg valueOflulalArnuum h resuii K Vuu earned smhg valueOfmequean enlerPuims lrequ2nl rehierpurhis reiurh result gelTilleO w smhg valueo each gelChargEO 201 11 42009 Customer private double amountFor Rental aRentalH return aRental getChargeo 1 Next Replace Temp with Query You are using a temporary variable to hold the result of an expression Extractthe expression into a method Replace all references to the temp with the new method The new method can be used in other methods More refactorings Extract method Remove temps And finally add the HTML report 11 42009 public smng mmrsrarememor Enumeration rentals Jemal elemental smng result ltHlgtRentalsf0rltEMgt gelNameo ltEMgtltHlgtn Redraw e U M L dl agrams wmre rentals hasMoreElements r Rental each Rental rentals nextElernerrto o 2 E 3 result each getlvlovieo getTilleO H H Stringvalue0feach gelChargeO ltBRgtn l add footer lines result ltPgtY0u Owe ltElvlgt smng valueOfgetTotalCharge ltEMgtltPgtn result On his rental you earned ltElvlgt porntslpyx H return result Draw UML Sequence diagram of Not done yet The conditional logic statement is suspect The switch statement in Rental is aRental aMUvie controlled by attributes of Movie getTmalChargE This is usually not a good idea Keep control with the data so 1 Move getChargeO to Movie getTutalFrequentRenterF uirts furall rentals macharge RenterPur nts getF riceCude furall rentals gEtFrEquEn But what varies with the rental Chan e type 9 Recall thatthe clients are going to change the types of rentals 11 42009 Situation Move frequent renter computation to There are several types of movies Rental For each type of movie we have different Compute the charge and the frequent ways to compute charges and frequent renter points in Movie passing in the rental points number 0f days from Rental We expect to be changing the types of Things that vary with the type are together movies in the same class Re lace Conditional Lo ic with p 9 How Polymorphism You have a conditional that chooses different behavior depending on the type of an object Move each leg of the conditional to an overriding method in a subclass Make the original method abstract How do we fix this To introduce State Replace Type Code with State Move Method move switch to Price class Replace conditional with Polymorphism to eliminate the switch Replace Type Code with State You have a type code that affects the behavior of a class but you cannot use subclassing Replace the type code with a state object Use if the type code changes during the life of an object Create Price class abshacl class Rnccl abshacl ml gcancchcca l class ChlldlensPllce extends Rnccl lnlgelPllceCude return Mcwc CHlLDR ENSl l class NcchlcascRncc extends Rnccl ml gelPrlceCudeO return Mcwc NEWj ELEASEl l class R egulalPllce extends Rnccl ml gelPrlceCudeO return Mcwc REGULAR l Move getCharge to Price double getCharge ml cayschlcm irlt result Ell swllcn getF rlceCudeO case Muvle REGULAR result 2 ll davsRented gt 2 result davsRented e 2 r l 5 break case Muvle NEvviRELEASE resut davsRented 3 bre l case Muvle GHlLDRENs result l 5 ll davsRented gt 3 result davsRented e 3 brea l 15 return resultl 11 42009 Make sure everything uses setters and getters for the type code public MovieStn39ngtitle int priceCode title 39tl 39 setPriceCodepn39ceCode Change movie s accessors public ml geancecode return pnce geancecodeu l public vold seancecodelnl argll swllcn argll case REGULAR pnce new Regularpnceu break case CHlLDRENS pnce new cnlldrenspnceu break case NEW7RELEASE pnce ew NewReleaseRnceu or ax default throw new lllegalArgumentExceptlon incorrect Price Code l l prlvate Prlce bnce abslracl class Rncc abslracl ml gcanccccccu abslracl double getCharge ml davsRented ml getFrequentRenterF ulntsUnt davsRented return ll l class NewReleaseF rlce extends Rnccl ml getF rlceCude return Muvle NEvviRELEASEl double getCharge ml cayschlcm return cayschlcc 3 l ml getFrequentRenterF ulntsUnt davsRented return davsRented gt i 7 2 l Outline Factory method Adapter More Desugn Patterns Observer Composite CS 3331 Bouncing Ball Creating Different Balls rv t2 Ea private static nnai String EALUVPE week 1 a public Euuncmg a lol n C circle eeuaismALUVPEm be l new oneie eise n C rectangle eeuaismALUVPE be l new Rectangleo public class Euuncmg all extendslava applet Appieil pi a ll ball To bounce different types of balls lelsel be l new Circleo l l 0121251 er eeee i Q What s the problem with this kind of code A Better Way of Creating Balls Example Cont How to bounce a triangle ball public class Triangle uuncmg all extends Euuncing all protected Ball createEall0 return new Triangleo pwate static class Triangle implements Ball public V ld drawo l r V 0121251 er eeee here l Factory Method 0 de ne an interface forcreatlng an object but let subclasses to decide which class to instantiate p raclurymmuo canmaeclass cummwmuun quotWWquot YacturvMethudO IvetumanuncreteruductO Bouncing Cars How to bounce instances ofthe class Cal7 public class EuunmngCar extends Euunclng alH prutected Ball createEallO l return new Enuncezhleczr l l public class Enuncezhleczr public vum mam l r mm rest at nude have l extends Car implements Ball 7 Adapter Cont Outline Factory method Adapter Observer Composite Adapter To convert the interface ofa class into another interface that clients expect adaptee upevatluno Outline Factory method Adapter Observer Composite A Closer Look at JButton How the button events eg clicking are handled JEuttun buttun new Jauttenr ok t buttun addActiunListenern2W OkEutlunListenerO private class OkEu unListener implementsAmiunListener public Vuld actiunPe urm2dAcliunEvent e System nut println 0k btmun pressedlquot l Dynamic Behavior human Jammy l CkBullaantenev aaMsnteenett VimMianeNmmede adianeihimee Vetsmuclt Composite Design Pattern To allow clients to treatboth single components and collections of components identically To define recursive data structures such as trees u 0 u m remw20umpunen0 Static Structure Factory method Adapter Observer Composite Example Composing GUI public class MyApplel extends lava appletAppietl myPanel add addmyPaneD l new Button addActiunLls nElO r ctlunPe urmEdO luv eaen l in itsenens l aetten enenneete Outline n 120 Subbuttun listeners n omunm mu actlunPe urmedO AWT Components Using Composite Pattern Cont public class BallGroup extends Ball private Set balls new HashSetO ll each b in balls is instanceof Ball public void addBall b ballsaddb public void removeBall b ballsremoveb public void paintGraphics 9H for Iterator i ballsiterator ihasNeXl Bal inext0drawg Factory Design Pattern Intent To decouple object creation from its use and to supportdifferentway of creating obje s To de ne an interface for creating objects but let ubclasses decide which class to instantiate and ow Abxlmleartmy makszduclO A create Cnncretanctnry Cnncretel rnllct makerductO Bouncing Multiple Balls Iterator Pattern Intent To provide a way to access the elements of a collection sequentially CnncreteIter ntm39 return new Concreteit39erator39o Example 0 Complex numbers 21mpthwa maleomplexlO Pnlannctnry makeCcmplexO 1 11an nmplex ltltcreategtgt Rectmgruurumry Rectang nrcnmplex makeCcmpl 2x0 ObjectOriented Modeling Class Diagrams Class selection description Instances Sometimes class and object are used to mean the same thing by mistake 11 42009 Object Class derivation description How do you nd objectsclasses Objects have state Objects have behavior UML Class Diagram Class Name Attributes Operations 11 42009 How to recognize attributes Descriptive attributes Naming Attributes Referential Attributes Recognizing Attributes and Functions Car speed dtrectlon Visibility in Java Class Relationships Associauon A connection between two classes Generalization Arelationship between a more geneiai and amore speci c class The more speci c can contain additional infonnation Dependency Re1ationship between two e1einents one independent one dependent An association that suggests that one c1ass contains another Aggregation UM L notation Association 11 42009 UML Class Diagrams Employee Name ID SelName string void The box on the right is i stance ofthe Employee object UM L notation Association UML notation multiplicity A customerinay have 0 or 1 sales reps A sales rep may have many customers The default is 1 UML notation navigability Arrow on association indicates responsibilities Employee m st be able to say what customers it is in associatedWl Customerhas no corresponding ability to indicate what sales rep it has Recursive Associations Example IProperties of the aggregate propagate to the pans as Well Paragraph IUnless there are common properties of pans that can be attached to the aggregate as a Whole there is little point in using a e ation 11 42009 Notes Navigability may be in one direction or both Unlabeled associations may mean Un nown Bidirectional Associations can be named using verb phrases Roles can be named using nouns Shared Aggregation The diamond is open not lled This says B is apart qu AismadeofB s TheB sarepart ofA Composition Aggregation Here the diamond is lled The part object may belong to only one Whole The pans are expected to live and die With the Whole If the Whole is deleted the pans go With it The composed class probably creates the aggregate 11 42009 Complete the diagrams below Aggregation Example Employee UML notation Notes SubtypesSupertypes subtypesgeneralization Inheritance Every subtype must have the is a relationship with its supertype Every mime These are also known as parent class Customer Customer Is also an H attributeofits and Child class A masses All attributes and methods of the parent are also attributes and methods ofthe child Corporate Reasons for using Inheritance Types of Inheritance Extension MovingPoint inherits from Point and adds speed and direction Restriction Circle inherits 39om Ellipse and provides different area and circumference calcula ions 11 42009 How do you specify generalization in Java Dependencies Shows an element requires another element One element is a client The other is a supplier server Dependencies Interfaces and Ports 39 uses The client requires he presence oftlliefsupplier abl ltpermitgtgt39 The supplier must grant some leve o I lt permission to the c lent Rmable ltltre negtgt Shows a mapping between two elements at different semantic levels The client will re ne the supplier ltltmterfacegtgt An interface de nes the Rumble methods that a user can abstract ltlttracegtgt Shows hat two elements represent the same concept in di erentmodels The trace s ows a mapping between the elements and is useful for tracking requirements ltltderivegtgt Shows that the client can be computed 39om the Nothing is inheritedby the sUPPIIEF implementerexcept the method signatures What are the differences between Abstract Class generalization and interface hat is required when you extend a class What is required when you implement an interface When do you use one overthe other abstract void moveTo intx int y No body speci ed Ifa class has an abstract method it must be delcared abstract Ifa class is abstract it cannot be instantiated Abstract classes must be extended InputOutput Classes Collection Classes in Java Collection and CS 3331 Major types of collections Sets bags lists maps De ned in thejavau il package Interfaces of collections Set Interface Method Desenptrpn aunts addAll Add an elernent rr not already present D Add eaen elernents or e r not present 1142009 Outline Collection classes Collection interfaces Imp lementation classes lterators Inputoutput classes Metno amen aunts addAll Collection Interface Method Desenptrpn eta Add a new elernent addWe Add all elernents or e rernoveo Remove an elernent removeAllc Remove all elernentsround ln e retalnAllc Retaln only elernerts round ln e clear Remove all elernents contalnso Mernpersnrptestrng epntarnsAlle Mernpersnrptestrng rsErnptyo Wnetner lt rs ernpty slze Tne nurnher pr elernenE lterator Return an lterator List Interface a Desenptrpn a lnsert p at tne rrtn ppsrtrpn Append p at tne end I c lnsert all elernents or e startrng at tne rrtn ppsrtrpn nu addWe Append all elernents or e at tne e rernovel Remove rrtn elernent rernoveo Removetne rrrst occurrence or p settl 0 Replace rrtn elernentvvltn p rn lrtn elernent lndegtlt0f0 Return tne Index attne rst occurrence of 0 ndegtlt0f0 Return tne Index attne last occurrence of 0 llStIteratorl Return a llSt Iterator fortne SuhllSt Startan frornl SuhLlSt l l Retrun a suhllst petween Index landl 11 42009 Map Interface Map Interface Cont Methud Deseriptieih Mam Dempan MW ASSUME WWW k ehtrySeto Set at hewaiue pairs rerheivem Herheivethe mappihgrurh keysato Set Eika s clearo Remuve all mappings values The cullectiun ufvalues 921k The value associated With k EuntalnSKEyk Whether euhtaihs a mapping reir k keysato EuntalrisValuEv Whether euhtaihs a mapping tei sizeo he h r at pairs isErhptyo Whetherit is Empty Outline Implementation of Collections C Iled39 r Classes Why different implementations I Collection interfa es 0 Implementation classes Iterators Ordering Inputoutput classes Class interface Deseriptieh Set s table Set Hash table e DLL HashSet LinkEdHashSEt TreeSet unedSet Balanced biriarytree Implementation Cont Implementation Cont Lists Maps 0 35 Wm DES W D Class ihterraee Deseriptieiri ArrayLis t Lis t Esizable array Map Hash We mm L BMW f39 egg IdentityHashM ap Map Hash table With identity eurhpariseiri E 59 E39 LinkEdHashMap Map Hash table and DLL TreeMap SurtEdM ap Balanced binary tree Hashtabi Map Legacy at JDKi u 11 42009 Example Iterators of Collections it t Counting word frequency titratgator publicstalievuidliequenee quotuninuii Slringwurdsi a me n Manor p ew LinkedHash remni r n r ltwurus ienglh rr MEWDd DESEHPUD W irnap eeniarndsKeme ds iiiDi 1 were insert e in tne eurrent pesrtren 23 P W SWEW quot 999 Dr remuveO Remuvethe last eiernent map putrwmusrrr new integerrr inleger map gelwurdsi inwarueor SEND Repiaee the current eiernentwrtn e i nasNexto Mere eiernent rn tne forward 7 mmmm F map MEMO mama mm H hasF reviuusO Mere eiernent in tne reverse StringwurdString rnexio nexto Returntne nexteiement System nut printinwurd l map getrwuru nexlirrdexo Return tne next index previouso Return tne previous eiernent previousindexo Returntne previous index Outline Ordering and Sorting Collection classes Collection interhces Partial order or order mP39ememamquot Classes Binary relation that is transitive gratqu Total orderif a lt b and b lt a implies a b rderlng Inputoutput classes Comparable Interface Comparator Interface biiE interraee cernparaterr publicinterface Cumparabiei F int eumparemromm u rnt eernpare obreet er obreet ezr l Metnod compareTo 39 MemOd compare Resurtltur rrtne receiver precedes e Pe uit lt 0r if oi precede 02 e Result tr rr nertner tne receiver precedes er ner e precedes tne receiver a Result 0r if neither 01 precedes 02 nor 02 precedes 01 e Resurtgtur ire precedestne receiver e Res tgt or it 02 precedes or Propertie 0r CONSIraimS Properties or constraints e a cumpareTub gt u imp iiesthatb nmpareTua lt tr e c cornparearb gt 0 rrnpires tnat c cornparema lt 0 e a eernrnareTubfEI impiiesthatb mm areTea f D e c cornparearb lt 0 implies tnat c cornparema gt 0 a cumpareTub e tr irn irestnat b nmpareTua e EL C comparem b 0 mpheg that C comparew b 0 e Censrstentwrtntne definition at equal r e r C t t m r a equaisb rstrue in a cumpareTub is u 7 on e W equa 5 e cornparerarb i5 0 rt 5 equaisb and b equai5a Sorted Collections Interfaces SortedSet and SortedMap Implementations TreeSet and TreeMap Example SortedSet 51 new SortedSet SortedSet 52 new SortedSetnew PersonCornparatonD SortedMap rnt new SortedMapor SortedMap rnZ new Sortedlvl apnew PersonCorn paratoro SortedMap Interface Metnod Desenptron comparatorr Return tne comparator nretRew Return tne first lowest key rastRew Return tne last nrgnest key neadMaer Return rnaplets less than R tarrMaer Return rnaplets greatertnan or equal to R subMaerrRm Return rnaplets between R1 and R2 InputOutput Classes Two types of inputoutput Stream O Sequential reading and writing Opened for reading or writing but not both Byte streams vs character streams Random access O Nonsequen ial reading and writing Can be opened for both reading and writing 1142009 SortedSet Interface Metnod Descnptron comparatoro Return tne corn parator frr5t Return tne rrst lowest elern ent la5t Return tne last nrgnest elern ent to Return erernents less than 0 tarlSeto Return elements greater than or equal to o subSetrot e2 Return erernents between at and 02 Outline Collection classes Collection interfaces Implementation classes Iterators Ordering Inputoutput classes Byte Streams DaraWM A o nrernputstrean nrterrnputstrean A Hmamulnpulsmzm Datarnputstrean gummyearn 17323041qu A A o nreoutputstrean nrteroutputstrean A Dataoutputstrean Hurramuumpulmm Strategy Strategy Design Pattern Intent To de ne a famil of algorithms encapsulate eac one and make them interchangeable Generic Multiple Function Plotter M0 emit Fluffm ml ememamso 11 42009 Generalization De nition Process that takes a solution to a speci c problem and restructures it to solve a category of problems similar to the original problem Example Generalize the plotter class to support mul iple functions Review Generic function plotter To plot arbitrary singlevariable functions on onal space a twodimensl Multiple Function Plotter Cont e u Deseriptiuh ihitM ultiF lutterO Hunk methud reir subclassestu setup mhetieihstei be platted ihito Template methud reir ihitiaiizatieh Which calls lnltMultlF lDttErO addFunmunO Methud tei add a mhetieih tei be platted plutFunctluno Aqullanfun lun called by paihto tn plutt e unmiuhs mheo Methud inherited frurn class Flutter that l he lunger useful in this class 11 42009 Write Java Code Stubs forthis diagram Static UML to code ame Person Address City State Zip Occupation getSalary Write Java Code Stubs forthis Write Java Code Stubs forthis diagram diagram m w i Write Java Code Stubs forthis Write Java Code Stubs forthis diagram diagram ma 1 1 1 m Class m as m 1 11 42009 Write Java Code Stubs forthis Write Java Code Stubs forthis diagram diagram In a 1 l Write Java Code Stubs forthis Write Java Code Stubs forthis diagram diagram identify abstram and concrete K k idenmy abshact and concrete mam 3 3mm methods and attributes Write Java Code Stubs forthis Write Java Code Stubs forthis diagram diagram 5mm creation m aide 5mm inwmtian amides dmwmethad FauanXrIr


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

Jim McGreen Ohio University

"Knowing I can count on the Elite Notetaker in my class allows me to focus on what the professor is saying instead of just scribbling notes the whole time and falling behind."

Janice Dongeun University of Washington

"I used the money I made selling my notes & study guides to pay for spring break in Olympia, Washington...which was Sweet!"

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!"

Parker Thompson 500 Startups

"It's a great way for students to improve their educational experience and it seemed like a product that everybody wants, so all the people participating are winning."

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.