DOC PREVIEW
UW-Madison COMPSCI 302 - Chapter 9 – Designing Classes

This preview shows page 1-2-3-4-5 out of 14 pages.

Save
View full document
View full document
Premium Document
Do you want full access? Go Premium and unlock all 14 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 14 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 14 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 14 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 14 pages.
Access to all documents
Download any document
Ad free experience
Premium Document
Do you want full access? Go Premium and unlock all 14 pages.
Access to all documents
Download any document
Ad free experience

Unformatted text preview:

1Chapter 9 Chapter 9 ––Designing Designing ClassesClassesChapter GoalsChapter GoalsLearn to identify side effectsLearn to identify side effectsKnow when to use method preconditions Know when to use method preconditions and and postconditionspostconditionsGo in depth a bit more on static (Go in depth a bit more on static (akaakaclass) class) methods and fieldsmethods and fieldsDesign programs the objectDesign programs the object--oriented wayoriented way9.3 Immutable Classes9.3 Immutable ClassesRecall that Recall that accessoraccessormethods only retrieve methods only retrieve informationinformationThey do not change the state of the objectThey do not change the state of the objectCalling them multiple times in a row will yield Calling them multiple times in a row will yield same resultssame resultsImmutable Classes are classes that only Immutable Classes are classes that only have have accessoraccessormethodsmethodsExample: String ClassExample: String ClassAdvantagesAdvantagesDo not have to worry about the dangers of Do not have to worry about the dangers of handing off references in methods because handing off references in methods because there are no methods that can modify them.there are no methods that can modify them.DisadvantagesDisadvantagesYour objects are fixed once they are created.Your objects are fixed once they are created.9.4 Side Effects9.4 Side EffectsMutatorsMutatorsare designed to change the internal data are designed to change the internal data of the implicit parameterof the implicit parameterSide effect of a method: modifying externally Side effect of a method: modifying externally observable data (explicit parameters or reference observable data (explicit parameters or reference types)types)public void public void transfer(doubletransfer(doubleamount, amount, BankAccountBankAccountother)other){{balance = balance = balancebalance--amount;amount;other.balanceother.balance= = other.balanceother.balance+ amount; + amount; // Modifies explicit parameter// Modifies explicit parameter}}Best to avoid if possible (otherwise, document the Best to avoid if possible (otherwise, document the effect thoroughly)effect thoroughly)Other Side EffectsOther Side EffectsWhy donWhy don’’t we add a t we add a printBalanceprintBalance() method to () method to BankAccountBankAccount??public void public void printBalanceprintBalance()(){{System.out.println("TheSystem.out.println("Thebalance is now $" balance is now $" + balance);+ balance);} } Assumes the printing should be done to the screenAssumes the printing should be done to the screenAssumes the printing should be in EnglishAssumes the printing should be in EnglishMakes this class dependent on the System class and Makes this class dependent on the System class and PrintStreamPrintStreamclassclassYou want to localize the input and output of your You want to localize the input and output of your program to as few places as possibleprogram to as few places as possible2How to minimize Side Effects?How to minimize Side Effects?Never modify explicit parameters to a Never modify explicit parameters to a methodmethodTreat them as constantsTreat them as constantspublic void public void deposit(doubledeposit(doubleamount)amount){{amount = amount = amountamount+ balance;+ balance;}}Pass By ValuePass By ValueTwo ways to pass parametersTwo ways to pass parametersPass by reference Pass by reference ––the memory location is the memory location is sent, meaning that the data can be changedsent, meaning that the data can be changedPass by value Pass by value ––a copy of the memory a copy of the memory location is createdlocation is createdJava only uses pass by valueJava only uses pass by valueEven objects are passed by value, since the Even objects are passed by value, since the reference is copiedreference is copiedWonWon’’t work!t work!public class public class BankAccountBankAccount{{public void public void transferTotransferTo((BankAccountBankAccountother, other, double amount)double amount){{balance = balance = balancebalance––amount;amount;double double newBalancenewBalance= = other.balanceother.balance+ amount;+ amount;other = new other = new Neither will thisNeither will thisclass Qclass Q::public void public void addResponse(StringaddResponse(Stringquestion) {question) {String response = String response = ““I acceptI accept””;;question = new question = new String(questionString(question+ response);+ response);}}class Rclass R::public void invite() {public void invite() {Q friend = new Q();Q friend = new Q();String invite = String invite = ““Want to go to the dance?Want to go to the dance?””;;intintinviteLengthinviteLength= = invite.lengthinvite.length();();do {do {friend.addResponse(invitefriend.addResponse(invite););} } while(invite.lengthwhile(invite.length() == () == inviteLengthinviteLength););}}You would need to do thisYou would need to do thisclass Qclass Q::public public StringStringaddResponse(StringaddResponse(Stringquestion) {question) {String response = String response = ““I acceptI accept””;;returnreturnnew new String(questionString(question+ response);+ response);}}class Rclass R::public void invite() {public void invite() {Q friend = new Q();Q friend = new Q();String invite = String invite = ““Want to go to the dance?Want to go to the dance?””;;intintinviteLengthinviteLength= = invite.lengthinvite.length();();do {do {invite =invite =friend.addResponse(invitefriend.addResponse(invite););} } while(invite.lengthwhile(invite.length() == () == inviteLengthinviteLength););}}39.5 Preconditions9.5 PreconditionsPrecondition: Requirement that the caller of a Precondition: Requirement that the caller of a method must meet method must meet Publish preconditions so the caller won't call Publish preconditions so the caller won't call methods with bad parameters methods with bad parameters /**/**Deposits money into this account.Deposits money into this account.@@paramparamamount the amount of money to depositamount the amount of money to deposit(Precondition: amount >= 0)(Precondition: amount >= 0)*/*/PreconditionsPreconditionsTypical use: Typical use: To restrict the parameters of a method To restrict the parameters of a method To require that a method is only called when To require


View Full Document

UW-Madison COMPSCI 302 - Chapter 9 – Designing Classes

Download Chapter 9 – Designing Classes
Our administrator received your request to download this document. We will send you the file to your email shortly.
Loading Unlocking...
Login

Join to view Chapter 9 – Designing Classes and access 3M+ class-specific study document.

or
We will never post anything without your permission.
Don't have an account?
Sign Up

Join to view Chapter 9 – Designing Classes 2 2 and access 3M+ class-specific study document.

or

By creating an account you agree to our Privacy Policy and Terms Of Use

Already a member?