Generics Core Java 1636406358

You might also like

You are on page 1of 13
10/68/9204) en Shanuy Jamadar \) Totroduction 2) Generic classes 3) Bounded Types 47 Generic methods & wild~card character” 5) Communication with Non-Genertc code 6) Conclusions The main objectives OF generics are to provide type Safety & Case 1: Type -Safet —> Araya are Eaneeaaal| to resolve type -casting proble” je. Wecangive the quarantee For the type of elements present inside Arrays. Stringl] Ss = new Stingliol 5 SCoJ = * Noor” 5 SC!) = new Integer (io) 5 \ce + incompatible types \ Found ; j-4-Inteqey 4 1 req’ ; j.4.String » i \ 1 Only String Objects Collection’s are [not type~saFe it. Weaantgive the guarantee for the type OF elements, pyesent inside cel\lection. Avraylist (= new ALO; | QBtving nm) = (string) A-get ©); : . ‘ ee @ | Ostring om = (St¥ing) A.get(1) 5 o Yn 1 @String oma = (Stving) 1 get (2)s A.odd (new Integer (10), (4) | MRE: Class castException 1 li Qt Case 2 : Type -casting | it's not required to perform —> Arrays : at the time of retrival peot ? ae joside Avra oe ean guarntee for the elements present josi y String] s = new StingT Io] 5 S{o] =" Noor" Stying name = slo]; ~~ “Ty pe- Casting Not Required . at the time oF retrival Compulsory we should per — Collection : type casting . type oF beco2z there is ho guarantee for the elements present i Colle ArrayList 4 = new AL@, 4.add ( Noor"); —s get ctore as object type. — EE String name = d-get 0); cE: Incompatible types i found : J.4-object ’ yeq’: j.t. string | String name = (String), get(o); Q 2 Salle Toovercome above Problems of Collections , Sun people fntroduced generics concept T Hence main Objectives OF Generics are @ 7 provide Type- Safety @ To vesolve Type-casti AL L= new arcy3 x <— beld anty type OF cee A\ CE : incompatible type — f ' Found : fl. Integer % L.add (°chitha"); reqr: jt. string. String mai = ae ake ; a | Type-casting is not ; re : Required - ! co > (Se ea 3 Ei [ALt=new ALO] [Atxstringy L = new AL | ie ccoun: Account al = new Account (| Account a2 = new Account F class GenDemo ¢ T obj 5 Gen ( T obj ){ this .obj = obj 5 psvmain(...)4 Gen) 5 Obj -getClass() -getNamel)); Neel $ ai ; public T getobjC) { GenXToteger) g2 = ew Gen return Obj 5 We can bound the type Para meter fora perticular rang® by using extends Keyword . Class Test < T extends Ramer 7 c Class {Test 4 \ | é \ ; | } \ | \ | \ \ ! i ee any type pass Number or it child classes = new Test Test t) =new Test | Test O> < Intege* p s Test {Stringy ta =new Test | Test C> 5 (x CEs Type parameter jt ( tans BSED tape) potin i+S bound. Syntax for bounded tupe Class Test < T extends x> X’canbe either class or T/F ee + jf xis class then as type parameter we can pass : either “x? € oy its dass typ glass class | ‘lf xisas tPF theo Class Test < Textends Runnable > | as type parameter we can pass 5 \ either “x type or its Implement x classes. Test LRunnable> t]= new Test C)* Test < Integer y +3 = new Test < In es CE‘ Type parae clase pally eteente Number’ Runnable )' ©) We candefine bounded types even in combinat® } also. Class Test < T extends Runnable & Comparable > Y) ———— { S Class Test < 1 extends Namber& Runnable & Comparabley (~) ee fa, e Class Test < T extends Runnable @ Number > (X) ae % “3 z Booz We have to take class First Followe . by interface next. class Test < T extends Number & Thread > 2 Becoz we can't ex Moré than one classes simulta : > WecandeFine bounded types only by ush & we can't use implements & super But we can replace implements | se with extends Keyword. class Test Class Test G “> AS type parameter °F? wecan take any java identifier Butitis convention to use 1? os Test | Class Test ee Test a f t 1) \ i) o } YoY Based on our: requ. use can declare any no.of type parameters, Class Test (4,8) ] class Test 4 (Cs) s Y S Y HashMap Tntcger, String) Ee HM 4 toteger, Sting > Os Methods & card chavacter (#) —> | m1 CAL £)]: —> Wecan call this method by passing AL oF only String type —> But within A metnod, wecan ddd only Stsing “type of ObjectS to the list By mistake, if we are trying to add any other type then we will get Compile time exror. to} C AL String> L) todd ("A"), YW ALoddCnuild, dadd(io); x —|mCALK9>4 —> wecan call thi: —> But witbin a method, We can't add anything to the List except null. Becor we don't Know the type exactly ‘ “nui is allowed becouse itis valid value For any type. m1 (ALX<2>L) LV Gddi(aa) sn Ladd eGions: = d.add (nalld; v } ‘ ly opera” = 5-shis type of methedesememnes@memmmable For resS ON ly OPEN 191 (AL< 2 extends x > 1) — > X can be cither class or I/F — if x 7s a class then We can callthis methed bypassing AL of eithey X type or its child classes. tf x ts an TIF then We can call this method bypassing Al of either x type or its implementation classes. BOT Within a method, we can't add any thing to List except null. Becoz we don't Know the type exactly This type of methods are also best Suitable -For read-only operation m1 CAL<& Super x ¥ £)] —> y-canbe either class or t/F —> if x isa class then We Can call this method by passing AL of -either x type oy its super classes - © > JF x is an f/P then We can call this method by passing AL of either ¥ type av super class of fm plementation class of X Object Runnable (x) < Thread y — > But within a method, Wecanadd x type objects and nal! to the List. vo ALK P> L = new AL Stringy 0; ~ ALL 82> 4 = new ALK Enteger7O > a ALL & extends Number> { = new AL < Integery(); (Wo ALX 2 extends Nambery4 = new AL < String> (9 5 3 CE: incompatible ~~ ALK Super String> L = new AL C5 ¢ @ Al <2) = pew! Aaa mae Unexpected type @M Avesye new ALK & extends Number C33 Class Test { We can use ‘T” within this Class based on our sequirement Public veid mico @ Pile 2 eeeeeea i 2) public <7 extends punnable? void mics pablic Maio purpose OF Aas oe Generic is “at ylapeserety Building & resolving problem of Generic) not rey? puebeacaes' * 4 required at at runtime Both applicable yet ' » Compile time Hence generic applicalsle also at compile time. Compi) e time —> For IVM Generic Syntax won't be available, Avraylist 1 = new Arraylist AL4= new ALC) ~~ [ Arraytist « «stringy L= new AvrayLis i Avraylist

You might also like