Class Note for CMPSCI 220 at UMass(35)
Class Note for CMPSCI 220 at UMass(35)
Popular in Course
Popular in Department
This 7 page Class Notes was uploaded by an elite notetaker on Friday February 6, 2015. The Class Notes belongs to a course at University of Massachusetts taught by a professor in Fall. Since its upload, it has received 13 views.
Reviews for Class Note for CMPSCI 220 at UMass(35)
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: 02/06/15
CMPSCI 220 291A Programming Methodology spring 2009 4 7 Effective Java Classes and Interfaces Items 14 16 2o 21 22 Effective java Item I4 You may be tempted to write a class like Class Point i public double x public double y This breaks Ehrapruaizoh Why is that bad What to do For each field of form Abc xyz Make it PthE or at least Protected Provide a getter publlc Abe getxyz return xyz Arid a setter publlc vold sethzAbc xyz thlsxyz xyz Effective java Classes and Interfaces Ten items ofyarying detail complexity Alate good to follow so You should read the whole chapter We will present items of greatest relevance at this moment in the course Problems with Degenerate Classes Can t change the representation without changing all client code no real API Can t enforce invariants rules Can t take auxiliary action on update or use I So shouldn t do it but rnaybe ok for apnmte class How about final immutable elds Suppose you have public rinsi Abe xyz e Mpgbtbe 0ky since it avoid some of the problems but Still breaks encapsulation rnakes changes harder etc Effective java Item I6 Implementation inheritance violates encapsulation Subclass depends on superclass details Makes it hard to change the superclass safely Item 17 talks about how to do inheritance ght if it is the thing you re going to do But now let s take an example see its dif culties and try to x it IHS detai s public class IHSltEgt extends HsshSetltEgt Iprivate cnt s u constructors ouitted goverride pubiic beeiesn add u e cnt return supersdde This is an ahhotaizoyt This particular annotation documents that we know we are overn ding the superclass method IHS deta s public beelesn addAll Collectlonlt extends Egt c This says that c is some type ccllecticnltTgt where T extends E but we don t need the name T here We ll talk more about generics later we expect InstrumentedHashSet IHS HS public class IHSltEgt extends HsshSetltEgt Iprivate cnt s u constructors ouitted goverride pubiic beeiesn add u e cnt return supersdde goverride pubiic beeiesn addAll Collectlonlt extends Egt C cnt csize return superaddA11 c public int getcnt return cnt IHS deta public class IHSltEgt extends HsshSetltEgt This says IHSltEgt is geytma n is any class or interface type no primitives allowed It also says that it extends HashSetltEgty a class for hash sets whose elements match E Ok so what39s wrong with It public class IHSltEgt extends HsshSetltEgt override public bcclesn sdd E e cnt return supersdde override public bcclesn addAll Collectlonlt extends 13gt c cnt csize return superaddA11c public int getcnt return cnt After an addA of three Item set Count 5 sl HashSet addAll uses HashSet add to add each element That comes around and runs our subclass method We could x 1 when we nd 1t but 1f HashSet changes addAll we can break 1n the future Problem comes from Overrldlng But that doesn39t look any better FomardingSet is 61mgan for subclassing It are a HashSet rather than oermmg it However It obeys the Set Lhte ram so clients Here s the code can use it like a Set Item 2 Function Objects Invoking aJaya method on an object typically performs some operation on that object Possible to de ne objects whose methods operate on other objects passed as parameters Instance of a class exporting exactly one such method is effectively a pointer to that method I Such mstznces are known as function objects Forwardlng to the rescue publrc Class rnstsltEgt extends ForwardlngSetltEgt overrrde publrc boolean add E e cnt return supersdde overrrde publrc boolean addAll Collectlonlt extends 13gt c cnt csrze return superaddA11c publrc rnt getCnt return cnt ForwardingSetltEgt FS publrc class FSltEgt rmplements SetltEgt prrvste rrnsl SetltEgt s publrc FS SetltEgt s thrss s publrc boolean add il e tatutn ssdde publrc rnt srzeo return 551260 rdrwsrdrng yersrcns of all Set methods We also use the word dEEganon for vaavdzng Safe to subclass thls because 1 won t change etc Also called a wrapper dad x Example Function Object class SlrlngLeng hComparalor public Int compareSmng s1 String s2 return s1 lenglho es2 lengtho Method orders stnng by length not lemcographlcally Reference to stringLengthComparator serves as a function pointer lnstance ofclass s a concrete strategy for stnng companson SIngIeton Functlon Object class stringLengtncomparator private stringLengtncomparatoro public static nal stringLengtncomparator INSTANCE new SlrlngLeng ncomparatoro public int compareSmng s1 Slrlng s2 return s1 lengtno rs2 lengtno Concrete strategy class is typically stateless l lence all instances are functionally eqmvzlerlt ingleton sayes unnecessary obiect creation costs Anonymous Strategy Classes Arrays sortstnngArray new comparatorltstringgto public int compareSlrlng s1 Slrlng s2 retum s1 lenglhorsz lengtno i Concrete strategy classes are often declared using anonymous classes Eacn call creates a new instance 39Ifused often better to store function obiect in a pnyate static nal eld with tlescnptiye name and reuse it Hosting Strategy Classes IIExporllng a concrete strategy class Host private static class SlrLenCmp implements comparatorltstringgt Senallzable public int compareSlrlng s1 Slrlng s2 return s1 lengtno rs2 lengtno IIRelumed comparator is serializaple puplic sta ic nal comparatorltstnnggt sTRlNGgLENGTchoMPARx WOR new strLencmpo IIResl ofclass omitteo Passlng the Function Object What type for the function obiect pararnetergt stnngLengtncomparator no good er allows only one strategy 39De rle a comparator mmfart Motbfy stnngLen gtncomparator to implement it 1 Strategy interrace public interface comparatorltTgt public int compareT t1 T t2 class stnngLengtncomparator implements Comparatorlt5mnggt 1 Same class body as before Hosting Strategy Classes Concrete strategy class need not be public to export a concrete strategy A host class can export a public static eld or a static factory method Item 1 The strategy interface will be the type Concrete strategy class can be a private nested class of the host Unlike anonymous class allows implementing Item 2 Summary lmplemennng the Strategy pattern is a primary use of function pointers To implement the Strategy pattern in Java Declare an airfare to represent the strategy create a raaa implementing this interface for each concrete strategy For single use strategies can use an anonymous class For repeated use strategies a private static member class exported as a public static final field wliose type is the strategy interface 5 Item 22 Favor statlc member classes over nonstatlc ones Th 5 about nexted algasag c1asses de ned msz other classes Can be donefomways w Statlc member c1ass Nonestanc member c1ass Anonymous c1ass Local c1ass Static member class example c1sss TLC espe1eve1 c1sss seselc me sf steels fleld me nf msesnce fleld seselc c1sss SMC steels member c1sss seselc me ssf e sf TLCsf me snf e sf TLCSf SMC smc new SMCO TLCSMC obj new TLcsMc eec Nonstatlc member classes I Each TLC instance can have many NMC instances that refer to it I The NMC instances can all access the TLC instances fields etc Thus the NMC instances have pointers to the TLC instances called TLCthis Static member classes Slmplest case Mostly an ssue of scope and access The nested class can access nan parts ofthe contaxnxng c1ass It an access contaxnxng c1ass nstance elds xt s not xnsxde any nstance ofthe contaxnxng c1ass It s lust as ef cient etc as any class 7 xt lust has a longea qualmed name Nonstatic member class example c1sss TLC espe1eve1 c1sss seselc me sf steels fleld 1nt nf 1nstence fleld Class mac noneseselc member Class 1nt nnfl sf nf 1nt nnf2 TLCsf TLceh1sn mac getNewNMC raturn new mac statlc mac n new mac error NonSta Ic member classes plcture This is from Java Precisely page 33 em as a new Taco meme m1 some mco 102 a some mco TLCSMC 510 7 new TLCSMC Typical real fe example iterator publlc class MySetltEgt extends AbstractsetltEgt most omltted publlc IteratorltEgt lterator return new Mylteratoro prlvate class Mylterator lmplements IteratorltEgt nonstatlc member class The rare local class by example a method pupllc lteratorltstrlnggt surrlxes rlnal strlng s class surrlxlterator the local class lmplements Iteratotltsttlnggt pupllc poolean hasuexto pupllc strlng nexto pupllc vold removeo y i return new surrlxlteratoro y why Because lulplements ls lllegal for an anonymous class Tagged class example contlnued pleuremeuale length double wlnth shape e shape new thls length length thls wlnth wlnth neutle area 0 smtehnshape ease new return lengthowlnth ease cream return Math prvrranlustrranlus nerault thrw new Assertlennrrero Uses for anonymous classes For function objects oneruse or multiple For Pma err objects Runnable Thread etc Within static factory methods Item 20 Prefer class hierarchy to tagged classes T ed classes are awa to im lement a class whose instances c igemseveawnavor P class Flgure enum shape macr 21th1 y or lnt codes rlnal shape shape the tag rleld double length39 ror rectangles only double wldth double tadlus ror clrcles only Flguremouple radlus shape e ShapeCIRCLE thlsradlus e tadlus Evils of the tagged class Verbose enum tag e1d svntch statements Hard to read multiple c1asses un39lbled together Fatter than need be Hard to make eld nal Must modify source to add another avor Compiler can t enforce rutlallzatlon protoco1 Type does not indicate avor Addmg a avor requires modifying every case statement Us g erarchy to do better Using h rarchy to do better 2 abstract e1ass Flgure Class Reet extends Flgure abstract double area 0 flnal double 1engtn 1na1 double wldth C1255 flgclglextegds Flgure Rest double length double wldth Clrcle double radlns thls39length length thlsrad1us radlus hmquotldth quotldth double area 0 double area return MathPI rad1us rad1us return length Wldth Easy to add another class Square extends Rest public Square double side superside side But only if Figures are meutabE Xhy
Are you sure you want to buy this material for
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'