0% found this document useful (0 votes)
31 views33 pages

Oop Concept

If you're a beginner who wants to learn the Basic Object Oriented Programming concept then this note helps you a lot.
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)
31 views33 pages

Oop Concept

If you're a beginner who wants to learn the Basic Object Oriented Programming concept then this note helps you a lot.
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
You are on page 1/ 33
4S TOmsierer oy a | Soe He moe aes ea eerie e/a ae Add Look if any -topte I i; 7 ; \ 1 1 lebyect | class Inheritance Abgheaction —pelymenphism — Encapsulation i| oO ct ‘ 7 Poy Galena presperchy method Teegant | ’ eal clase/ogen attribute/state unelionand pacedune, y." ilin ae Pr method is Wasically a behovieun, A class certain multiple wbVhed- | | delined lueprunt ov pretvtype trom A class is a user which ‘objects awe orteated . Containge yarttubles; ‘method conshzuctore, block Pa shodement, class on wterface- An obgect is the ‘instance ‘negult’ ee alecs! ea ma Time: Dae? |, Abstractor Abstraction refers to the ack of mepnesertting essential | telus we without eluding the background details. | Hiding unnecessary dat “from he users » and moking i || tne application as usert Ariently then Ws called abshracton- ac With preagreamming perspective, Enclosing Base and: -tmethed’.. within. a glass, would be called encapeulution - 1 ui | Blyrmecphicm: Ws an ability of am obgect to dake | | { | Ymony forms. | \dhertanee ig when an object aquines \he cones i oF anothere object, Example —— Nehi ele | es | con ruck. local Local vaniebles ame declored insi Class variables alse with The ¢tatic keyword In o class Obsect oni oriented, platform independent, simple, seeure, porctel anchitecturol-nelurcal, robust, mubithnead, “Interpreted righ perclonmance, dishtibuted, dynamic: Noriobles In Java class/ static \nstance deo methods, constructors ort Uset wk eclaned In a class Yuk side method, \nslanee variables are 4 consttuctort an bleck- kenoum 06 sei variables arte declared Nout outside relvod» consuctors or wee K: Soe il Twhat ane the differences between diglastorke a 9! onl +) | 6 | Rp integers 'F' 7 character, 04" —y sheng, oe i - 4 e | Modifiers < | \, « | (a - | | Access bet eteal < i 4 shotic — closs and metheds @ u overs. \ e i inal ‘ i] defourt i abstract - ted ' @ eee gynehronited ond Valdile | public (Arveeds) © i « } e | Modifiers ore keys thet you add’ those defination -to change — § their meaning « « | ‘ | ‘ || Meaceess modifiens in save specifies accescibility of dale iE , member, method, constniuctore ert class. ( | | | “The priivele access modifiows is accessible only within the class. default The ysvale Access ynodifiens 4 S$ atcessille only within package. [= public access wodifiers i¢ gecesible everywherte « ‘Sub mei et Ber 77 “Wee protected modifiers 1s accestible within package and oukide the package but Through inheritence only. ‘ e Me fh 4his example, we hove eneded Uae eee lic class A the two package “ pack and wey pace”, pee es { : ' atected void msg0 . he A class of ' pack’ package is = woh ID { Syste. ovt- print (“Hellow"); public, g0 we can accessed trom outside } he package. But ‘msg’ method of this package declawed as prolected. i deg ks port pack} at ocean accessed from ovbide Vrough swherclanee | closs B evtends aX public shetic void main (String? 9s { the class only is | | | | B obd= new BU; oby. msg) 5 z f || tinal emadifirr fore inating, he. twslementations Wie, methods and ~enriables . t Abstroct modifier fort crreahnay abstnack classes and metheds _ ime a ad | Non = Access Modifiers i static modifier | fore eneoting alass melhads and vorisbles, * * + * a a a q a i smeimaned and woletile modifiers whteh ame used for thneads. Seovmerr Class CgSdemi out! to reofers) " Standard output deviee” | sydem-in’ Ao nefens "Standard wput device” i bey > ” import java.util. Ceannere” package -to use Seannen. class. ——> class ____— inshonee vartebles _——— method int ane) = new int Cte] \ d ‘port Javan util ™ 5 I is used -to Senger al he eS ierefnees fram Ave ‘Sevarcehil’ paclege wn Gave prugrtomrags. Lengunde ffae Method and Methed uerloadins @ Ea Tenet Desi 77 Fae _Methed “Weve methed is a catlection of stolemert thot one greuped together +o perforin specific task. A methid must be declared within « ¢lass | Methods Standard Libreny method sere defined methed con create Jreire wr” wer method \yosed requicements such oS pruntld, ned\ntO nett, nevtline Uso dened Method Cotegenies ®D Methed wrth no angunents with no on ee vale " ” . e arguments ne: angumerts " riotunn vee ® " 0 argum ert n reelurn velue- sub: Method end Method _Oxerlonding Soe = Gh Add two ‘imlegere values using) method i public class Methedt 4 | public storie oid main (Greing ta) orcas) 4 | ink a= 10, b= 55 | | i } i | H sum (a,b); I ‘ public static void sum Gat a, int wy Systern- out-printha (The sum ise” + let); i 5 : it 5 | Here we ean also use olgect ike . -- a = public ghatic void main (Grange aregs)4 Methodt aby = new » Methed4sl)? wr asito, int br 30/ obd- gum (ob) j= Sa Ts Method without using obyect VF we wok 40” call any methed ‘without omy obaect then we have -» deelore the method, as static - public class Method’ { public static void moin: (Strang t3 ange) wk acto, ee b= 6) mk c= mor lab); system. out: pron (Moxie Values" + e)5 5 public static ink max Cink nt, wt a)4 ink “mot—valve 7 oe vad) ee max_yolue =n4s else max value =NZ; return mat value; |.» Method using. _obaect tn as SN OD ie tar 7S || pubic clacs Methods A public ghahe void main (Strengta args) Methodd ob} = new Method t) i wh a=4o, b= 30; mb ¢= obj.mar (a,b) System. out prim tn ("The mayimumn: “+ )) y public wnt mar (iat mt, wt mw) wrt max—value ; og (ns7 nt) mar avalué = 045 else ; max—value= nt; retumn =may—value ; . sub:_Method seed es Tiwet 7 Vf es - 7 hen iarelats | hag hyo ort more “method by, same name but different poromelers, is known og method: overt oadin => Method overloading increase the reeadabilid y of the prcoepram Methad Overloading, oo | By changing number: By chomging the Data type et argument i “O public cls Methodoverleeding void sum Gat ov mt BDA |] Syslern-out-prantin (at6)s y Noid cum Lind o, int & jiette){ Syslem-out: print n (atb+0); OF | paste lati weid main (Strep OD ongs)4 Nethodoverdnadwe) obj new Methedoves oO: void gum (asuble a, deuble by duble ot aba gum (40/29) ob}, gun (50.82) 5 ob}. sum (50 60,70)! ov. gum [405,906 aoe8); Tine a 1 Rahy method cit is not possible by cnongig aoe I eehuien Aype of method only? i S Because ot ommbiquity, els see hows ambiguity mary octurcs j pete class! Adder { static wt odd Grto, it &)A | return atb; , i 5 | > stotic doublel(sek an wt BY return atk x | public class Test I public void static main UShang t) omg | Sylem- out prantin ( pdderesodd 1.9) // ames gaity | {| | | | Syslern -ourt prevatibn | Addere, odd (n-ni)) / fene, = = = - - e e Ls e © e deterrnfime: how ean java which gumO wethed gould be called 9 | So -huva compiler renders comgle Hime enrere \E you deelone ometerts- Ake game method having same pom yy J See THCan we overload yore man() method 2 aes, by metthad overloading. We com rove any number ok main methods in & class by melhed overioodingy But wm ells man method whidh recieves string, array os ancequrierts only. Les see public class Test} public static void main (Grringt3 ong ){ Stem. ou pret cna, wie singh) ay public static void mam (Grong oxy) . main with “Sees Syslem-out -prantln (« y pilic state void eran () 4 Sqslern.ovt prantn (main without args") J 5 pe Nees Wt meted oserlanding VF we oy Shee spre veka Ay of motholstKene must be differences in the amber of paromelers Daa scree cad eee sub _Vedelined Module Language mt) Car le me UML ¢ r Generalization (\nherittemee) ——— \S- A Relationship : : | anY | Association Aggrecption — Has- A’ relahonship eompesition : A _genertaltzartion. ig a yavoromic relationship “between a more general classifiere and a morze specitie classifier. \s— A_reolationship BANK \ super /generatizetjan | Zs aS extends i : evlends tee Association > Relationship Luicen -lwo sepastale classes which eglablishes th: ‘i Trough their, cbyect, Know ag wthas_ A! rrelohenship, Each class is \ndeyendert. they can evist without each other. Course s has [Feachert | Asseciction | Unarcy + Binary class A has alass 8B. Beth classes known akeut each | But class B nasnit class A — A \ hos | 8 [A J hos B a ay | Aagastegation : a Specified fren Association, whole / Parc} Relahonchip . Bofh lasses aia iwdépenderb. Bsr+ class can evist withock i pobilercles . | Poko whole Pract Composition rf |B cies of asc class depends on whole ‘class. | : fl O i a é A Specified stronger’) rom of Asscetation. whole/parct rrelatonship, Sub. Timer Sener ance open Nechuve-2 amd go to page 49 weapacity : double Dash Board mprice : double = produchiweart: Sing = prtabaction are Sting a, ‘ ‘ Sub :_Iwherifone and polymorphism Soa ime Dae 7 - ——————, | Single wheritance ¢ ‘ ‘ public class AY A ; J ar | public class B erends ag l b i Multi level Trhenitance + public class a4... } BB public class B eydends Ay. cea e public class @ eylend A4.A5 i | {) | | Hierarchical Inheritance ‘ rica! snhertitance | plic class AQ. Y oN public clase g extends { 4 ple lass @ evlends RA. Y | | i { | | | a = SSS | | Maliple: Inheritomee + \Al public closs AY... -F le public closs B4.. -T Le] | public clas @ edends ABA SS f/ doeot+ supose Method werertiding 1 | \S subclass (child) has the same meted os declared in he parent -class, is known as ‘method overtreiding) in Yava- Method overatidingy is used foo runtime. pstymort phism - Rulese Sy The method must have the same name as parcent olss FH 4 ew the. Same poramelee Hoo" > Thene must be |s-A rdationship- Liwherdtaned) | [ Supere_keywored Time Baie 7 i “he ‘super’ Key wored is similarc “to ‘this’ key wored. | \ Usage, of supere keyword ¢ i ' i | 4. super is used + refer immediate parent class instance vial | oe en Run th Compile — ime. eee Super. variable s © ‘| © da Superr is used +o ane immedi te parent class method | q Supere. method ()- a i « 3. supere is used +e invoke.’ immediate porrent élass mmshuelor eee suet ‘ : if « « er ° mo Ttp! Vom r ( 4 { t ( " (gretned merlot) on (methed overrciding)) Sub-Cenehuictow_ond corgnucan Oweeading CTI Satan Temes Dear 7-7 4 Aconstrusbort tm aya ig: apetlel tnethod. Used te initilize objects . Rules; Foonshtuchr name must watch the class name 4#Tt catt have a pelurm type (net even void) tconsttuctor is ealled when the object is created. * Al closes hove constuctors by default. Ub gait dow+ ereste a class consnuctor, java creales ohe of us and withale Ahe variobles with default volue cuch og O on NULL- a closs Bike { dass Bike =b. compilers =p Bike 4 T ; t Svomple: public class MyClass wt x5, public static void main (Grong areys)4 Myalass oby = new MyClass; Syglern. owt. printhy Lobd- %)i 5 t uts Of i “Jove Constructo 5 (Ve ae == = Default Bee aed st eataes | ne-arg construct? i} Defoult Construehsr (ne-erg) public. class MyClass Ant x5 public MyClass of 4255 i y public static void main (Shang 3 args ee oe een cient O60. 8 Oe i Mylass oby= new MyClass (); i! Syelem- ouk prvtin (obs. x); 5 ? Jt pve dass Bors Ant height; wh widths public Boyt OF syglem. out: prantin Cr Box ereded")i Ans heigt = hoy Abis. width = 20; 5 public static void main ( ghemgtd oe) | Boyt koxs = new Boxtl)? systema -ourk prt (vox nesaht) Syslem-ouk: provatn (wos iat) Boxy bord = new Bort LIS sychem: out pritin (wox2 veg)? Looe wit); Syskum: oul. print\n 5 | sub : SS Parametertined _Conghruclore, publie class Qox2 4 | | ink widths public 6x2 (yea, ih 4 i | ink height: | gqslern.ovhiprontin (" Box aneated *): Ais height = %7 Anig.width =i 5 public static void main (grimgtd axgs)4 i Box boxl = melo Boca’ B ser 2°)s System. out prontn (ooxs- wetghh) > System out prciethe (oon wi uth); Boxy bond = new Box (soo.aee) 5 System. rk priintin (boyd. eighth) Syslem- out. prantin (Loexa- width); x } sup; Cominco Oueclanding on ME "O =e = Constructor Overloading, is a eencept of having public class. Demo mone thom one_ernsinwchans willy diffoner eee parameter: list, in such a woy go thet eoch 4 ; dormed dong S)4 congiructore yehrms a ditenent ask. “_— 5 public class Box deme (yet 4) private int height, width; ‘ } public Box\{ heght= 495 width= 19) 5 Woe) W'S nek tpt > ess Same pamamelert- WE ton wes iene pemameere Nike: pebic Blink he pie BoX Lint height, wk wath) { get et Aig. Retght = height? nig. width = widths | q \ gute hate wid wean ( Ghargyt3 orgs Ger wy ce need BXU5 ffoutort = 22ST ex b2 = new Bex (290); O oukput = 20,39. Bx Wz new Sx (ger tos)¢ outa = eng Ba vA = new Box Oj Mosteate 40-45 “saslem. satiprontln (oF width) i sylemovkgnindln (bts herp)? ieee rere sub: Method _ Overertidin \seritan ee) me TT publ class, Amimal{ prblic. vsid ‘makeSound (24 Sister oizkirainty ("The Arimal makes a sound") i y a wilic class Deg edlends Arrimal{, public: void make Sound 04 Spemoud.grontin( The degy ores!) a oY 5 if pobtce class Main { il : ; : i public sktic void main (sringta angs)4 Animal animal = new Avimal UK, animal: make Sound CO); ‘Dog dog = new Dg i * “dog, rake Sour () 5 Aramal ‘onothondg = ne, Day Os rose | avatherdg-makesand 0 ff we deg, berks | Bymaghts) —<—<—= Faces aeeceee teeta eee ie i a ik ei ek i a i i Sub :_Eneapsulation — % fore Encapsulation is the process of Landing date and She! connesenng methods Umdert ao single methed . Also Wdma serbremation details and protecting Data and Wwhoviourt of the prayect. ot ai dass will be \idden from sed ony Anreugh the melhods known as data id vagy In encapsulation, the variables othert classes, and can acces of Aveir current class, “therreforte, W'S ako Rules: a. declare closs varcololes /atireibutes as _povdle . 9. provide public et and get methods ko access and ugdot® the value of o grivale_vardioble - B The apt method rchurens Ahe vareiable vane BH the gol medhed sels She value lo: Serle 4 ‘ork Mame ; getvame. \)* gelpame O; |= Eiwnle So |) public class Pereson{ private Sheng) mame; public. ved setName (Sheng, rewrlame)4 Ahis.name = newName; J public. (Shang getName A relunn name; 5 J 1 Rblie class Maint public state void main (Sanat 3 orgs )4 Person obj = new’ Person L) ‘ * nye vole vardielbles oh}. setName ("Minhor")> rr v access with settere and aptten matheds | | Syslern: oust. promt (3. getName U) i rystem puct: prty (ost mel) bet ae | Encapsulation = Date Widingy + Abstrachen | By declaring Variables as private, we can achieve date hiding. we cant access W -trom oxtside this || class. | Absteas Hon: Highlights “the sevice ‘thet ore oHening without | explaining intetnal design / secformition ig the: ‘eoneepy oF Ness Example Using ATM eand — | > we ust swipe the Card > Enter We password Sy De Ave Arcomsaction We dent Unow “rhe internal procedure. Bema a user, we just need fp \now how tr use fhe cand - Arerlogy 5 ROAH Hidewey ae Werteased “Flexibility” lier % TTeshns code is easy. ! < sub: Aloshraction foes es Time Cae: 77 ~ if : i ae. i Way te Rdmeve » Alestreciehion. E : H « ‘ « ce Abstraction class : ji Tntersbnee ; (o-a06%) (460%) ‘ Avshracten class , SS pA. class which declared .. sith dloshtoak Meywisel mig | Known as an abstract class. ‘ Deses+ support rnulliple Anhentitanee leat can have aksheaet and nen- absheaet methsdg ii i| |* Tt can hove constructor, atic wethode cand fmol method: wt can have any -lype of wartable (otetic, nen- state, — : ROR ‘ptetneds | A melted which is declared as abstract and doesnt hove implementation i$ know as, an ckhcoation method - examples , peli. obsact aid aries oO; "Proust eal ‘with o Semeolon+ public olostrrack class Nehiele< public abshach vyoid mei) \ public. class Caw exends.. vehicle 4’, public void rane OF Syglem. ov¥- rl (« ee see) y i " gublic | glalic® veld snot Lonagia 8 Core 04 Gadd new Cor Oi tA movel) } sub : ft Tine: ‘Oue Ty Twtereface ln Jove fey, sill 1] An wlerehace: is. Muepint or lemplale of a class, similar to the class but difference has alshac} H ened ond static ee eoptgeeeetnosaeseo" Cd Bp Interface decsvi} contain any 2a HH Inlereface’ cant | be. declared, extended / 3 ited by ‘glass, 14% Civmplemented Ly a elass. ® Muliole- Inherctlome ‘eappnt, Trlernal additional by -the Compilere yrlenface Printables, pobre stedie Anal ant min oS? piclte absheact void pruntis wersface. Privrtable hr mme 5 void prints Funtoble. class | | | class extends | public wlerfuce Drowingg puolre void draw \); 5 public class Line “Becks Trasing 4 public. void draw 14 Salemsoukprintin me draw a Vine) 5 public catia void moun (Gromer ongs) A line \= new Lue 0; we \ draw

You might also like