0% found this document useful (0 votes)
9 views45 pages

Module 3 Java Notes-1

The document discusses object-oriented programming concepts, particularly focusing on class hierarchies, inheritance, and method overriding. It provides examples of how subclasses can extend superclasses and access their members, as well as the importance of constructors in establishing relationships between classes. Additionally, it highlights the significance of dynamic method dispatch and polymorphism in Java.

Uploaded by

sikandernote
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
9 views45 pages

Module 3 Java Notes-1

The document discusses object-oriented programming concepts, particularly focusing on class hierarchies, inheritance, and method overriding. It provides examples of how subclasses can extend superclasses and access their members, as well as the importance of constructors in establishing relationships between classes. Additionally, it highlights the significance of dynamic method dispatch and polymorphism in Java.

Uploaded by

sikandernote
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
Mo dule-0 3! Inbsttance ¢ Tobeftance & one of he coroustnes of abject — Pocause tt allows the Creatteo Onented programma ie tYrstjte Bonk of, hievarchi-cal « —>|Using Ihetbance sypu or create & esab class Hak saps +8 Commo? ao a set dated Ment. | +eontehlory | Taxa a clos —trak & @nhatted UW called acduserclard — he class That dows the Johattag a called 0 subdo! |S. | (ars. —s|q dubclau & % & eeale zed ver ato a oh) & supe cl tL aherk all o}, ac an stance yagtables and rath | toed by the eupe clatt and adds WE van \ unsg ue olemant?: Tphuitance Rast porate tH Jp tohvst aelaags 4 slengly compe oe i oe eoto anotbe by osting rthe ssi a ste follousi pore” creates & cupesclasa colt 0 sub class aed loved A {| A dia | eceonple }, golreattance I] create 4 coupes clad class A a " 4 ‘ ‘v6 oct ak) Sata vord show's () ae et Lata (thee “ \ord showk cBychem ouk- patle (Hk y+) 5 vod sumcr Byctem-out- pialln ("tajpake 4 CHd5 4 class StmpleInbesttance £ publee stalfc votd main (Shing avast DE 4 oupwrob = ow AC)5 B aubob = new BC )3 Il te ouperclars may be used by ateelh, erob.§ = 10 5 wobj} = 20% Syste ut: + Nontenke Loe obs" a. Tho %} C yy ae aS 5 System: out- protla a I The subclass has ans to all yublic manbe of PH ouper class. #1 \ | Gub0b-1 = F's eokob.j Se r et bik ae 4 wide a By chen « outs f atin (Nconkentt of subob + ")5 cubob- shows MO) 5 ‘sabob+ chow C) > “gyshero- ou pate 5 pe Syjtun ouk- paetle (“sen of a3 and * % cubob-; ‘gubOb- (un @3'" 42 olP Content8 * supudb * {and} ¢ 10 20 arvana cks eth 0b * g and j * epg 4:4 Bt Bic th Hi afl ht Q aub0o + gayxk * ap o} a cars Ldaatteo eg shows? Hor cnteds, yest the qeoual jose gn wits a gupeeclar? lows aubeclassnmt \\ boda o} claw “To bertt iad ah o} the membes | o} He cup a \those _ members } o} the Sup Pee clays tel - bp a class bYerarchy., private ‘members vemalln THR program contafns an error and wl) net compfle I create 4 pastas ¢ rtf is, I) publfe by default pivate fot 5 5 lipaivate tv A || | Mpls § & nok acceratble hers. j class B® extends AS | ot total 5 | vord sum() total ela ERPOR , } & oot accesetble 5 oC} chi: a aoe lata Acowr a public static - rsh (Si rt | « B subOb =rew BU) 5 a) | subdb. set 9g (101195 { ¥ cubob- sum (25 f | Lychem-out-piiatle a2 Re program wll nek comyile 15 engde tee sum(? epetbed ol, B yuatfon. Stace 4 & declared on coe 6% & only ace epaible by othe mambus- of 14 ousn clas. & dlardes have 7° access + RL me Practical E yi b= = er a \ all vulp alla q more pre. ca) prarnple wal veo othe the pours o} gonerttanrte- aw Hi gn a Were 0 chagt ("Total 2, fy! cubob total ) 0 Ud" pt. the ew cl eM called an ae ar ant wight , 3 turn sth & belie % depth 5 Bose klefaht eatends Bor < double voekaht 5 Boableight (double ww deuble bi Jouble dy double width= > hdght = b> dy cl & al woulght =m5 SaaS DenoBoxle publtc ctalfc vot Nat big Sie —wpybox lt = “rnifber? = 08 posit (39) Mero vol 5 ae a oe svolume (5 em = 0 paatin (( (WNdume , ny nea ai ; ical ya ar Aa sytem: Sd yaloe) 3 fe Hs ae svrolume OS oh nyo a tat vols ] Hem: out panite (Neluses Systern*e phate Ce e yb a Gr a. weigh) AY balosn olP + Volume Et myboe! a er 3 weight Oh mybozl wm 248 Volume miy Pow 2 2 he 0- 94 eight 2 robo? % 1086 i oe ae Serote callt ee 1s e igo B & used thi ae Jo constr " a yen re eupacas A oh. & Using sup. to (aj), Superclars Conchuetors SA subclass caniicall construe F dejtoed by TH i cayiant ty Se pra fea fer Vere: supyr (osq- lest) 5 arg IEst- cpectltes any AYyUments oetded by -the ce cr % the superclasg » F [supe 09 musk alusags’ be ther Atrck ctatemunt |eotecut-ed eaede a subclare conctructor- il A complete Ymplementatfon oh Baorkleeght | class Box £ | vate ‘double, width 5 | I ete Malle ‘bdelt ¢ | povate double 1h 3 | Baze (Bore ob) ¢, = ob- hefahts os ob. Box (double ww double hh, double 4) =W, beet 5 Tey Hespk= 5 2 hog. 5" voles 9) I hoot 3.8 Pe ork. wo bght)3 oA) ae * pr eile. 0% ¢ mee Mao oy. Bee ia a a ete) 5) ri (Musdyht oj myclone &. "4 ¥ coetght 3° * ! th cube Livelume C)4 { / ; * Eten vout-pstntlo (*Volume of mycube a" vol) stew: bad « petatta-(*uletg ht of my cube & "4 ragcube suoeeght ).9, “Splée od SpBotla C)5 «| ofp =: wolume eh Wnybor! ts 3000-0 Weight — of mybor! fe 34-3 Wolume o} ‘myhoxa B& Qh.0.\., | Weight of“ myboxe ts [Link] 6: I. yolume ‘s mybox2 BL —\-0 } deg ht i mybor3 & —I-0 Jos" volume, 0) myclene && 3000.0 } ketghh oh myclooe & S43 | Volure of «tm Glemoe 24-0 * | ba dght oh omybe i Qo - a ! ' , i? ttey 1 or dup. _ ; i es AES eond \se ~ TUF! e , prees tp tthe, supercars ao}, ths < Tre” decom en, o| |ezecept thot alia | eubclats 'e wht ch ured. apes) wsage hes, He folloustag qeieal on | super snumbUe 4 Hehe mnember co? pel & rvaskable thes accood. oer” } stualfoo $ hide membeot b Conctde. thes steigl clas At anti 25 clasd 2B omtends AL RL FS ei Cnty 0 js, Py Oe aay TEs. (be e class supo.4 sd rou CL ay i : fable ("8 % superclass + supa? gabelass " m3 System - ouk- wh System: out- pi abla (89.0 Sule shave , beer, using rthal constct 0}, ool a Jupes +f pajectly a ceeptable “eupuctars of, anotha- ‘Given threes classes AWB and'C, | o}, 8 aoktch ®& a subclass of A udhan thin fype of othialton pecuias’ each ~$8 Pybufs all “the tratts jeurd % all oj | Bupesclasses lathe care’ C anbetls all aspects a} Band A ht t& used at a super clans + He subclass Boaek) ment toh create -the subclass called shipment. § |-+8 all of the strats o}, Boatlaletgb and Box ) aod a feld called cocks whch holds he cost 9}, chipping such 4 parcel. h | wu coca ple jos multilevel bPetaschy . class Box v pivate ‘double whdths porate clouble bee bts porate double Lent 5 Box (Boe ob) $ watt = ob- wo8ctth 5 beige = oh. height 3 dept = ob. ap 5 15 {Salve Box (double w, double hb, double d)¢ \ wo? 3 ive 3 Le ek eid « go bay —Yusdatte ty Leh : i We YY? ) | Box Cdouble Adib = hebbt = aa fy dephh double volume C2 a s, gion tte 4 hetght * Lips a Claas Boxlelatyhe ceeterds Box & double weight 3 Booleeg ht (Bore uldight ob) £ super (Cob) 5 y voetght = ob dodight: 3 ponutyht Clble cy deal b , Jel death Saupe (wi bid) > : weight a*ink Box bletght C7 € if ‘cdpet C05 e208 ht = -15 a Je m) £ ds sonia Vaeh) 509 “ rt Cdoubl " A : ; Sab Ot qe & (Cw bidim)> : WE Ne rie ShEpment ©) £ > > ; 4 es Hits hus 4 ( 4 cost = -1; : éhEpment (cloiible den louble 1m double Os super (len my : 9 3 ECs fea Freable h rdouble ele double m clas8 demo mot S publec statte vord malio (ching argat ) £ ShEpmant- “chipmen). = ‘new shipment (0) 20,15, 10, 3-41) 5 8 munt- oe mont Q = new " tae (03) 241 0-46 1)-28) > double vol 5 vol = shépment 2, volume ( ); ae | Sete, ("Volume of shipment 2 et | Systern- out « prfotin ("dletget of shipments ts bil shipment coetght) 5 | Lystem- oud -pB tla (“shipp tag costs by chipmeot-|- cooky seen oth ' 6 os she ey ON Ay ‘ eee A ey rh! | s 44 SGal\ >> Becta, Ml apes fe EO prope " ao peep on ) w g you Uy) oy geo eeu fp ert | are 2B. bMS o -MUTIOK Th fF 5 po Ri ddiys oor 7 Tyme ert Miccomlum ott, bs umpr + d\o geet + 7 dds | “emda rie: cetn eile «) uytuud poo-anythe pemedyre ng caved to ybpmy) olive -yro- ani he (fons DQ eyed ‘ 4c yum] nD yess 14700 + anphg yt = = C_Purmod oyun MS = on iy B Sayer 4q).0 pos aS RT AP. 5 Sh e ms are = is eye -Cls Epcithes lk |G he supuclast- a: eigen ateatctld 0 ("intde class call tops. ee public. basal wetd wits (hey ang Df Ce Ke low C095 4 4 Op : dnstde | Als tonctuctor Thetde gs constructor Tatde’ Cs conshuctor Method Ovenssdin mo nial class hferarchy 1 when a method ta sub ~Claxs hot the ‘same cname and ay ¢ gna at a method Po 948 supe class rHhen +he “eth of Bo the subclass % aafd +> ovestde the klhen an ovurtddin mutbod %° called rom wits a eubclax will aloayt ae ‘Venton sp method defined ae aub clas ned Vewston of the method daft wll be” hed t care actly st ‘Sti ee i + as e Ve frag Ah ae & ord dew 4 Sythe out: poate ("8 ie \ sie oD By eakends AL . aes y pi Cant a \ %E bY pt) & earn ka05 L 3 void) chow? £ mee cay (atk) {5 4 Oveutde £ public ehaltc. votd mato (Stig tint BR gubOb per B Char Ds 4 subbb sthow 6) & , 4 Th. output a chousy “WOE WY) k:3 namic method Atspatch ps the, mechankaro y ~Wwhich a call fan eveutdden muthod 2. wesol¥ed af oyun ime y-vathor: than “compile, me. [Dunamte metbod 4B pach Bier becausé ) moe poly morphea: hous Tava wrplenants sun clara? Gelvance; yqufable can refer 404 chiet. Tava user rte fact -piresolve ca > ovuntdten methods at run tame . len on overrtdden method & called “Hough a superclart ‘exehuance, Java determiner wh*ch verstor °}, the | muthod to execute based, upon the, mt o}, the object bang refpord jo at the Lome coll oo: F Usta Nbetract Clascet \ t You | can regulne nat cutato enatheds |b ark by cubcladsed by spotpyeg he abctrac type mach eon sometimes ve ved tb at subclasile These mithods are dome Ab ited tesponatbilthy because they have 0 A speck fed & nthe superclast, Thus « 4 ieclesd ee \okesstle theme TE cannok atmply use te ¥ fe de}tord +e supuclats To declam 9° méthed , use ThE gral loom t x pe fb skact Lape name ( pasametes Sixt Sra fe rtm Mare - mutthod)) 1h oie Whee 8 oe At eae vot «calle dt Ay att Roa \ Syptern: out . aol ('natde ale call he rete") % ; , a : y Ae class © C eattends ne void callme (1) rel ? ate cuteprfotta (nade C's calle aythod’)5 i 13, ; Webess Tepate publ’ aria Fad ato (an oye i. ahuare > TH N abjeck oh pe B b= nw BOOS NH i oh tapeB [ : Cco=mw COs 1 objeck oh spe C th 5 loblaio o vefounce of ApL* v= Oo mefers to an ® abject” rcallodt 73, Weal ASRS oy ne webs aoe wefus WO 3 pice yy callme o yl calls B's a e203 \\ ie vetoes 1 Sf sacallme (5. N calls Cis) Kos cths ba20 Nan _ A's callme enuthed — ‘ ide Bs Callme merhed a) les) Gls” calle uthed. iF i creates one eoclass called & ang MBit |B. called ‘B gy Bubclasses & 97 leveutde , callmecy declaud & 4 Snetde She mato? method objects ol, Biype fi8a I declosedl, Also 4 rrefounce oh, Hype Hv called declare), the program then 94 tuen ie a 7eFe te each Bype 2} ebjeck to yp and wses at Tet to fbvoke calle 0), [dhy Ovestder Methods | | Brdeelelen method’ allew Java to s' ost! sunt tad +0 object ~ mosphtsm « egnpatico. B epte ‘i ere ali fox ont eae 0’, et allows a qenueal a to specthy mne¥bods that ust! a | to all of oe destivatives ¢ |-to de}toe the specthfe gmplemantalioo ° of —hoze method - fo Re om Using Abchact Classes ° Thos we Rtualtoa & which “you wll voc} f whines & Supt clatd shat declosek ate chruchuss give, betractfe a wtthouk portation a eorngl Lam } een! foa } evuy mithod . , F nie om Aeneb you ell wast tp Create, onl “Wayines @ gen 3 x d' Shared ‘by all o) THe L- cubelaas Ho yt ee test Saag Peo ach; yyw want some way to encine trata eubclars dora, todeed , overtefde’ all necens Hoda Ae Javale solution + thee ed a abstract meth od. tAny class sthat contafne one ov mere abcha mithodS must also be Leclawd abcract . To Bi declare a class abstract you Ae uae he abctract kuyword & Pronk o}, the clast keywoord Ot He begtontag o, th clare Avslaratino ecld o} an abchract ola tg. an wabcenin lava cannot! be grectly ta ctarta sted wth the nud uated. Such objecld awuld ) ' sels . be cause 'an abstract clast & oot bn at de ord. ye caanet deolass abshact ankles (atl abctract ctatic matho hay dubclard oh, an, abehract elas? mutt thy, Great als an muthods » fe tae 6 oh be tse, © daa abstract. i mpl eka ap O| nls ea i oh Thun arn be one obje et ulin oo (Y This %& 9 chneaete clasg 8 eatends yerd callme (DL ' Sifter: oud-piatln ("ps Renplemantatteo 6 5 class Urbebaict Dime 4 { [aber pull etal word main (8hing ng Dt B bsnw ' BO)5 ; be callme > b> callretoo (5 clas A Oe Ae clasel % he ee ho abject o| endantiate: a0 abctract cla el & vot posatble +o —labebact clase cannot be. heed te gattantiate ob Hob , con’ bes ded -to creake | 0b| eck refeun cet, | pequse’ Tavals approach dp run Have polymonp 0 eras Ah rough the axe o} saperclan Thus St must be poretble to create pan abstract -elatt aerhal C00 he ty to aanbelert object er | 4% vabetrach class Frqwe pe , double , fio d , t HI double > dim a3? yy | epee Caeite ai; double b) £: | and a5 . dima bs a ] Iosga & rou 00 abstract metho oe double areal) 5 class Rectan le extends ana a Reclangle Cdouble a double 6) 4 super Carb) 5 Mel-to ry Joule. areatd 1 evade i é [Link] -pralle (“tnstde Aneo jor Re a D9 retusa emi x dim & 5 wen 5 B hsof hy 4 t claws Trfanale eatends Raw Tan le (double, aicdaubley Saye ay he {9 ov emelal double asal) apnatle ("Dnstag Histag trial ork Tyhittabte | hein } [the Hujoord “nal hag three usat.& tt = D> % faa Ve dared +o Create the + eal be |) named constant - Bk dvout dion ESS Y str et 4g) Prevent) BS Ustnl nal +e Prevest tnutkence | fna) to Prevent ovesidiog | Pk Ustog ulbsle reine ovuatding & one 0 Maya's mock ree ofl [Link] aka be 1? when " will » Tor dtsallous 0 res to revere ey am occu Ree os a method |vom! Betns ov widen . ° ely mod?hex at the etast of qe declaration. Methods declared as final cannot be oveutddea class 44 Final vord . . meth? $ . Systenr oe - poatle (this | wa “Arnall method -) 5 3 clas, B adhends ht word wath (4 a yttem- -ouk* poatla ie Tle aga |.” Because meth (), & 4. Moud td re oveutdden & B. Th You allehipt +n Heme cmt, wail rua , : So |VERROR | 5 ovate raed call 0 “le ad. . 1 a pe ¥ fret a declares all) = x ac edt at {tral Final clare ite aig Gl da) 2 ’ lth’ poll clase & allegal i class B arts $ N estan! cant dubelosd gt tbat : br. Ob; ect class FThus. & a. one tpecfal ‘class Object da “defined by Ts We subclasses of, jsbiect “objet All ofby. classes ‘ : l& a dupuclas oh all othe classes. Ja veleen ce ed: a} type Objeck » can vefex +9 4 li él, tthy, class. a 1 arrays ore’ anplenunted ag classes tape 0 ject can alto _ a method heh ia vosta b dub B,: the aha os are available. pe. re at ‘ =! Cyto ak the object bing hoola equals Cob object) ere an % yotd Pnaltze (eo sealed before an apised object & se cycled. mi Glew’ | get( laste) > chit he claat ol) an object a: Int haabCodeC ) > re. Stee hath code ataoctated with the t voking object otd bolity () > Resumed earecutfoo ha ~tbread getty ©N the ®vokia abject ad potty All (’) > Resumes eat oh all breads | wating on the Sovok?a: ebject . Bring Joshing () 9 RolunAs fgring that eb object . i Verda |roakt C) —> wat on ancthy, Yore vord woot Clon mill®seconds) oh errecud% Vetd booth a rrfllteecoadtd, ta Nanoseconelt ) god « Use gata ti ; «muted Ustag the keyword eoteface » you can ‘fall a tie from tn a ee bles ce you can speck ruohat a clard rouse do, But nok hou % de — Serie ~ te Afrally Amar class. Hea Reed ccaatssies x and, Ams et ase. Aeclasud uSthout ans boty =a au tan dehfoe Potebaces shat | eksurpptions abouk hous ag Penplemen lonce % & dubcoed | nq numb o} classed com | Emplemant an @bulaceValoo one claw co? Fm p\ermant oumbea o\ tot ehaces a — Jo Pmplement 'an tober ace a oko, nae if he, complete cet ol, ods, duhfoed by Hee, tobufa ce. a > an ttu}ace me ehontar 0 \*y poviding dn abehrack aifpe a dod make e) & tok ela € beMage ain(s - sordetbal- nance Cpesareter—legk ) 5 1 (pad. )s nae imetbed= narve 2 (pasamater ~ Let) ‘» oh aypt Ffoal-vdunamea = value 3 ctype teal = Masname s 5 bates Bray bles 3 wen hype method= name! Cpararneter LBs) 5 “type Fal -vasnameN = value > 4 hen no accerr specthi acces yeaull8. ue eluded en dafoutt de chasad Pode o\ fotelace Pinal and tae = Vautab) es can be gempleman th | declaw Tons “Thy ade sen pli | meaning thy cannot be chan id by “he | class raust also be i saltced . All methods and Yas “sd as. seog\t cH public. —+arn example Jox 0» ttelace dalgaitien ft dedleseR Ml | shen gle ®t k that conbains ons metred called callback,’ hat jakes shogle teg Ue posamallcs 9, Pr 39 ee ty, te a votd callback (tat prcaro) 5 " 3 Eimaple on ont * im lemenking ‘Tnteo haces ae an eesjace a been jo froed Des cc classes can emperor ‘not eokupact ust a an Sot eface clude “he ae Chae debeod Class dabritog mi te CARE by ame wt elace class classnameleacterds ON tr minh TL, Drehace ig) class “boy ye the Cabtback a small example clart that Fonplernun ebeufert clase Cites Genglemanlt Callback bite vot A caltback, (at pt dysterd-ovd spfedta cabtbl called ig class Tutlfac public static, | ¥! ca\\back, = y CG oth 84 P)> oo & : * Dae % 29 2) Callback. t, ‘ae ~~ S 4 Bred! catlbache, | ‘ oye Yeattback (Rat param) | elas © lest plement Callback, & | Apeblic, etd catthack Cink pet yoke ponte (1 cattbaol called with +P) > Clas Another Clent Gmplemuots callbock public vord caldback. (Sat pt System -out-piotln (“Hnothe veto of, caltbatk’) dyskem-ouk phatln ("Pp squand B& N+ (p¥PD ‘5 clare Terk face at public at word mako (Shing i Callback, c= new Ciont C95 EP) rote Clint ob= nun Another Clest () > 1 €+ call book C42); ag t 1)4 a c=o0b% 6 qe aller D5 ae ey ce Anis 74 i | % | tatlback called He ‘ | Another yeutor oh Base | p squared fe ITH |Weated Tobacates & ' es a ee Sot elace Can be eel a bx anothur otetac- duh om Chilled ward bee SEtface OFF nek vested Btoface can be declaxed 2% pabite pivety jor potected. } Ag Hee» enteskace Hepa tft boolean GuNot Negative (bt 2) > tis B tenplosen uted DOL publtc oh 8 ac Nare Cot z) sh wetun #40 9 false + strue 3 4 class Nesked Demo, abl®c ghalic | ‘adie 4 ye NublTF OF New BOs 4 bod Avie et nt site (1) ty 34 ; gaint 19 Sock Saqattve Dp 7 £ (oR? PeNlot Negettyve (- 2) i out: potla( "nes ood be dteplayed ) 5 hee developed ia class called Gack that Frnplemant O wBrople | FPoud -ahze shack Thu axe many\ wan Te 1 op plement a stack. fa example «the stack can be of a Fyaed afar or TH can bere wable" the stack can alto bebeld Ban a Va Lfobed Ut, q binary wee and . : evince crack tu ") a wee sick, [roe-- 13 3 class re tat? x ‘Be. vod neko Shaq 2" L clatte NO oC a OF publfe Froudsteck pula ee FoadStock myplack2= 28 4a Rot B20 45> ax) a ran ; $3 (tor Pek rt ‘ vat sade © magn? erty Ta eh “Bava, util, Random 5 r ShasedConstanls € Rot No =05 r Bot YES=1 5 Mt MaArBe= 25 Tol VATER = 35 Gt Soon= +4, | Ht Never=S;5 4 | class Question Goplements Shared Conclants $ } Landon vrand= heww Pande (5 ft ak OO ¢ Bt pob= Gat) Coor rand. nextDouble Os ae) Teduon NO¥ N3or- elec of Cprob <60) pel YES; I 807. | else oP Cpoob * 5) Dae, THEY LATER 54 tf Cpwb <8) his) Wi mtwn Soon, Wi) eke peta NEVER 5 |) Q-/ Class AskMe mplemenls Shoal Constants & Artic VS Fopd ©! absdoer, Cash wesatt 2 switch Cresult) £ case Wo’ Fon 10) Sipterp Out pont! LNG ~ break 5 coke WYRE AS 5 Any cy System out pootlo( TES )3 breaks case MAYBE . Maubelde Syste out ponilo ( 4 break 5 Case Pohufis thon Poteapact + tm provide lemenba torts fe “f method aftoed wr Boteapace G haflan ce - chat | hte ace Ag } q vord methat) 5 | 4 votd mets 205 a B eatends AE yord: metb3() 5 class My¢last fen plemeks BY publ veld methL Cg Syskero out: priotlo (Implernast melt 9) public vord meth ac) m* yous -poiatla (" Laaplerment metbhra ().U3 dyste 3 public vaid meth 3 C De. Sysker out poatlo (" Srnplement me 4 30) a \| ———— Nes | class TRExtod tS a public static votd rain (Ching ast D £ MyClass ob = New MyctardC d3 ob. methi()5 ob- methd@03 ob. meth 3095 =e Default Interface Methods ___ Asexplained earlier, prior to JDK 8, an interface could not define any impler whatsoever. This meant that for all p: interface were abstract, cont: revious versions of Java, the methods specified by an no body. orn This is the traditional form of an interface and is le \ the type of interface pee Coe eee discussions have used. The release of JDK 8 changed av this by adding a new capability to inte al calcd et face called the default method, A default lets es you define a default implementation for an interface method. In other words, by use ofa \ default method, it is possible for an interface method to provid | le a body, rather than being abstract. During its development, the default method was also referred to as ; an extension method, and you will likely see both terms used. tion for the default method was to provide a means by which interfaces out breaking existing code. Recall that there must be implementations by an interface. In the past, if a new method were added to a popular, widely used interface, then the addition of that method would break existing code because no implementation would be found for that new method. The default method solves this problem by supplying an implementation that will be used if no other implementation is explicitly provided. Thus, the addition of a default method will not cause preexisting code to break. for the default method was the desire to specify methods in an that are, essentially, optional, depending on how the interface is used. For example, ‘an interface might define a group of methods that act on a sequence of elements, One of these methods might be called remove( ), and its purpose is to remove an element from the ‘Sequence. However, ifthe interface is intended to support both modifiable and nonmodifiable ‘Sequences, then remover ) is essentially optional because it won't be used by nonmodifiable Sequences. In the past, a class that implemented a nonmodifiable sequence would have had. to define an empty implementation of remove( ), even though it was not needed. Today, a ‘default implementation for remove( ) can be specified in the interface that does nothing (or throws an exception). Providing this default prevents a class used for nonmodifiable Sequences from having to define its own, placeholder version of remove( ). Thus, by providing « default, the interface makes the implementation of remover ) by a class optional. ‘tis important to point out that the addition of default methods does not change a key spect of interface: its inability to maintain state information. An interface still cannot have instance variables, for example. Thus, the defining difference between an interface and a class. is that class can maintain state information, but an interface cannot. Furthermore, its still ‘ot possible to create an instance of an interface by itself. It must be implemented by a class, Therefore, even though, beginning with JDK 8, an interface can define default methods, the {interface must still be implemented by a class ifan instance is to be created. ‘One last point: As a general rule, default methods constitute a special-purpose feature. Interfaces that you create will still be used primarily to specify what and not how. However, the Inclusion ofthe default method gives you added flexibility Default Method Fundamentals Aninterface default method is defined similar [Link] way a method is defined by a class. The Brimary difference is that the declaration is preceded by the keyword default Por scam; le, Consider this simple interface: Ee ees Se) _ ce method declaration. // It does NOT define 4 default isplementation int getNumber () ; J] This is a default method. tot ice that it provides 7/ a default implementation, default string getstring() { return "Default String"; MYyIF declares two methods. The first, getNumber(), is a standard interface method declaration, t defines no implementation whatsoever. The second method is getSi it does include a default implementation,n this ease, it simply returns the ‘Default String’. Pay special attention to the way getString() is declared. ts declaration is preceded by the default modifier. This syntax can be generalized. To define a default method, precede its declaration with default Chapter9 Packages and Interfaces 221 Because getString( ) includes a default implementation, itis not necessary for an {implementing clas to override it. In other words, ifan implementing class does not provide its own implementation, the default is used. For example, the MylFlmp class shown next is, perfectly valid: laa | // implement MyTF. class MyIFImp implements MyIF { 77 only getMunber () defined by MyiF needs to be implemented 47 getstring() can be allowed to default public int getNumber() { xeturn 100; ) } “The following code creates an instance of MylFImp and usesitto call both getNamber() and getString( ). // Use the default method. class DefaultMethodDeno { public static void main(string{] args) { nytPImp obj = new MyIPImp (11 / can call getWunber (), because it 1s explicitly implemented by MyTFImp: Syetem-out .print1n (obj .getNumber())/ // can alec call. getString(), because of default 7/ smplenentation: System-out -printIn (obj .getstring()) 7 } ‘The output is shown her 100 Default string [Asyou can see, the default implementation of getStringt ) vas automatically used, Itwas not pecesary for MylFImp to define it, Thus, for getStringt) Implementation by a class Is ‘optional (Of cours, its implementation by a class wil be required if the class uses getStringl) far some purpose beyand that supported by ts default.) iris both possible and common for an implementing cass to define its own implementation of a default method, For example, MylFlmp2 overrides getString() clase MyIPImp2 implements MyIF { see TT ieee for both gettunber( ) and gatseringt ) are provided ; Lente ie gecmanber () return 3001 ’ nS EAPC e, when getStringt) is called, a diferent string is returned. "AMore Practical Example A hia’ 7 their: ‘assume that we now want to add a the stack, enabling the stack to be re-used. Thus, we want to ‘0 that it defines new functionality, but we don’t want to break but with the inclusion of default interface ean be enhanced like thi i // store an item i Uf retrieve an icon cleax( ) has a default, it need not be Uf implenented by a preexisting class that vate sntstack. default void clear() { [Link](*clear() not implemented.) } * @way to gracefully evolve interfaces over time, and, * away to provide optional functionality without requiring that a class provide a Placeholder implementation when that functionality is not needed. One other point: In real-world code, elear() would have thrown an exception, rather than eeblaying an error messuge, Exceptions are described inthe nest chapter. After working through that material, you might want to try modifying clear( ) so that its default implementation throws an UnsupportedOperationException. Multiple Inheritance Issues As explained earlier in this book, Java does not support the multiple inheritance of classes. Now that an interface can include default methade you might Be wondering ifan interface ©2n provide a way around this restriction. The answer is, essentially, no, Recall that there is Chapter9 Packagesand Interfaces. 223 still a key difference between a class and an interface: a class can maintain state information (especially through the use of instance variables), but q FE “The preceding notwithstanding, default methods do offer a bit of what one would normally associate with the concept of multipte inheritance. For example, you might have a class that implements two interfaces. If each of these interfaces provides default methods, then some behavior is inherited from both. Thus, to a limited extent, default methods do support multiple inheritance of behavior. As you might guess in such a situation, itis possible that a name conflict will occur: For example, assume that two interfaces called Alpha and Beta are implemented by class called MyClass, \What happens if both Alpha and Beta provide a ‘method called reset( } for which. balk “declare a default implementation? Is the version by Alpha or the version by Beta used by MyClass? Or, considera situation in which Beta extends Alpha. Which version of the default method is used? Or, what if MyClass provides its own implementation of the method? To handle these and other similar types of situations, Java defines a set of rules that resolves such conflicts. First, in all cases, a .s priority over an interface default implementation, Thus, if MyClass provides an override of the reset() default method, MyClass’ version is used. This is the case even if MyClass implements both Alpha and Beta. In this case, both defaults are ov verridden by MyClass’ implementation. ‘Second, in cases in which a class implements two int urfaces that both have the same default method, but the class does not ov verride that method, then an error will result. Continuing with the example, if MyClass implements both Alpha and Beta, but does not override reset(), then an error will occur. Tn cases in which one interface inherits another, with both defining a corto! default method, the inheriting interfaces version of the method takes precedence ‘Therefore, rds Alpha, then Beta’s version of reset{) will be used. continuing the example, if Beta extent e It is possible to explicitly refer to a default implementation in an inherited interface by using this form of super. Its general form is shown here: InterfaceNamessupermetloodName( ) ss implementation take ror example, if Beta wants to refer to Alphas default for reset) [Link] this statement: pha. supe Use static Methods in an Interface nother capability added to ints JDK 8is the ability to. ore static ce eal em nssnesci independently of any object, Thus, no mpl entation ofthe inteCiast iA DESessaiy, and 99: followed by a Here is the general form: InterfaceName-staticMethodName instance of the interface 1s required. i imilar to the way that is called by specifying the interface nat Notice that this is si - ‘shows an example of static method in an interface by adding one to MyIF, shown in the previous section. The static method is getDefaultNumber( ). Treturns zero. public interface myIF ( // This ip a normal" interface method declaration, 7/ 1 doce WOT define a default implementation. Ant gettunber () ; // This ie a default method. Notice that it provides // a defaslt inplenentation. default String getstring() { Tis "Default string*s 14 This 1a a static intertace method. 48 static int getdefaulemunber() { 09 € ecu pes return 0; ) J ‘The getDefaultNumber() method can be called, as shown here: ime defwum = [Link] () : As mentioned, no implementation or instance of MyIF is required to call getDefaultNumber( ) because itis static, ‘One last point: static interface methods are not inherited by class or a subinterface. er an implementing Private Interface Methods Beginning with JDK 9, an interface can include a private method. A private interface method can be called only by a default method or another private method defined by thesaame interface. Because a private interface method is specified private, it cannot be used by code ‘outside the interface in which it is d ‘This restriction includes subinterfaces because a private interface method is not jahe “The key benefit of a private interface method! is that it lets two or more default methods uuse a common piece of code, thus avoiding code duplication, For example, here & anotNeT versfonr ofthe IntStack Gor Tat hay to deck methods called popNElement() and skipAndPopNElements( ). The first eturns an array that contains the top N elements on the stack. The second skips a specified number of elements and then returns an array that contains the next N elements. Both use a private method called getEElements( ) to-obtain. an array of the specified number of elements from the stack. // Bother vereion of intStack that has a private interface // method that is used by two default methods interface Intstack ( void push(int item); // store an item int pop(); // retrieve an item Chapter9 Packages andinterfaces 225 // ® default method that return: 11 Shel top m elemence on the pram Jefault int () popNElenents(int n) // Return the requested elements return getElements(n) ; 1 A dstaats method ac eeturn an srry tht conta the next n elements on the stack after skippi ae * ng el seater ine | seipambopanictents ine skip) 46 al (ag // Skip the specified number of elements. getElenents (skip); Return the requested elements. return getElements (n}; } J/ A peivate method that returns an array contd taint 4/ the top n elements on the stack 4 weir: privace ine{] getBlements (int n) { int {) elements = new int{n]; for(int ic0; 1

You might also like