0% found this document useful (0 votes)
6 views16 pages

Java Module 3 Notes

The document provides an overview of inheritance in Java, detailing various types such as single, multilevel, hierarchical, and multiple inheritance. It explains concepts like superclasses, subclasses, method overriding, and the use of the 'super' keyword. Additionally, it covers interfaces and abstract classes, emphasizing their roles in achieving abstraction and polymorphism in object-oriented programming.

Uploaded by

18jayanth45
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)
6 views16 pages

Java Module 3 Notes

The document provides an overview of inheritance in Java, detailing various types such as single, multilevel, hierarchical, and multiple inheritance. It explains concepts like superclasses, subclasses, method overriding, and the use of the 'super' keyword. Additionally, it covers interfaces and abstract classes, emphasizing their roles in achieving abstraction and polymorphism in object-oriented programming.

Uploaded by

18jayanth45
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
Object vented pregiaroming Hh joxa Ceesa06a3 Madale-3 Conberlance Trier ces} © Debne whertance and ist the’ APferent Aypes of nhettance in java (eye) - propaties fmm one clrss (pevent clo) ist ancths class Cetld class] is called as Inher tance + Perens eq wivins class ts abo called as Super closs ot Base chu a Ghd cle & ola colle =f Geb oe os Devived cls + Supe class const have Rnoledge of Sab cless * Buty Sub class is having now lealge of panertt Class and ifs own class : FO geughe # Types ef inheritance ip jase hen a class inhertts another class, t+ is. Frown o Single inher'dance ~ Examaple * Deg class inhetts Animal clase. class Animal void eat O : j Septem out. printl (feating.- ys Class Dog extends Ariirnal wick bart O Systems oad. printin (bos og. 2)s Class Testify her fen ce{ public static void main (Shing og (Df ' Dog d= Keo Deg (3 As bavk O : joe a eto: Aofp bas big. - [Link]- . te Maltilevel Taber dance When there ts a chain eo oe ele ee) of inheritance i+ is Example «- class Antmal A : sid eat O . lee s : Sytem ch eprintte Ceating-- »s E eB 4 ae Glass. Beg void bow OY Sep tern eoud, printia E bas bing) J class Baby dog ertendls Dog t void weep OL : Sytem: out. printin (weeping: ns exkroh Animal { J ; class. Tes tin hevitance? { public static void tate Cslring angi (Df BabyDeg d= bew BabyDeog lds As weep Oi ds bark O3 Ar eat C5 p 7 o- wp Merachteal Trherttance Whhen hoo or more classes inherits a singk class, 14 is known ag hiererthial Inhesitanc . eur (eoagey (cent) class Animal Void eat OL- Sypters soeet « pay HD, class Dog extends Animal { void bes ¥ Of Systern vouch. PF j 4 J class cat evlends Anirral void eve OL Septern ocak. pant & eamnp le tin Ceating- 3 iti (bax ting: ys in Emenstng Es), Class Test Enbaitance ( public state wid mad Cstring nga CI Gat cz nee Cot); Ce menmal); ‘ c-eate); wy Multiple inheritance (ostng inter faeke w_ jee) , te cow AL (com ] eer clas €] Anteface Flyadle { wid Ply Os: al inde face Seoreommable{ 5 void swim (> class Bird trplements Flyable, Stotinmable { spablic void PIyOF Systems. out. printin CThe bud Ries. } public. vid swim Of : : } Systers « put »primtln (The bisd Seoteen 3 public class maltple { : pe bic gtetic wid mais ( Stang ty ay) Bick hiv = new Bud oy bisd> efly Qs bisd « Vind ys 5 5 orp Bod tha Bird Swim o— YO ybsid Inher is 4 yb J inh Hance (Ceombinntion of Muttple 4 thera! : Trt eS 7 uses mx of clases and interes | Cramplt i Class Ariroal public void cot OF System, outs peartlncthis eantrnadh COtS y3 “Pood inleface Flyablet void Py Os class Bis erterds Animal tenplemensts Ligedle{ public void yO] System: outs printle Cte pid Mies?) class Deg ertendk Asimal { Public void batt ye kn ETE che bar fe.) y System vot pre public class HU br { public state ved modn Coe CI 0092) Bud bird = reo Be id vo oa iC peal cat 0s brid Ply Os Dox dog = nee Dog (1s ie eat 03 J J deg» beat C)3 ‘ o— . mI ‘ boas OF the hevidance > ® What * woPortance of TMlustate the Super Fepwoorel with an example “Ceyay . © the Be Sopee oo S82 is a vehi abl object. 16d te ne fee on TeNCe versiadle ; ae parent clase Sil fetanc, IP cree the imtance of subchss, an Fo weferna ROTH class ts cuated ‘mphcily sahich Yo Supe aeleence variable I & Usa 2 : FoF ja09 Soe tage ee ee poset class instance vasiable 7 We con use super keyword to acces the odode Member or Lid of parent class. T+ ts udecl tf pawrt class and child class have game Pel. Eromple + Class Animal { String color teohite”; J lass Dog extends Animal { [ * string ae ~ “black; thts hides coler in ariel. void’ printGler CD Sastem. but. prisstin Golo); U pants Dog claer caler y Spm cect. prittin CBaper colo); A Be anivat 5 Chss meen’ public sdatic vei main (Stargl] arg0) Dog d= new Dog C) 3 oe “y oof get Pat Color (Is 2. Sexpe is used to invoke superclass (parent) conte + the super Fequanc can ako be used to invoke the | parert class comfector Crample clan Af ints; Private int p> A Cinta, int b)f fas jeé> wid adds CH int b2 fiefs : j sptemout. paiatle (4 Cr) e) tF)s J class B cxtenck a( jot BS . B Cinta, int 6, int oy Super Ca,b)$ kecy J Wid addie Of Sp tem. oct .printlo Cun Taster. cut .printin (p+ ps Aber bes ff ts ivarte . System vout. puntin Ges e)s, J 3. Sup is cased fo invoke apes — clos metheg be usd to tovele the ~The Super Fecpoorcl can ako mnecthecl « child Parent class mmethacl cohen parent class Class methed names are Excenple de ae class Animal Wid ccc on Sytem-out n ect} printle CALI anima y3 class Dog exlencts Animal { wid eat O) ve System «ots patntle Ceating bread 3 J wid bask Of Sesto: out> punt wid work OF Super: eatc)s bask 05 (nC bac bing: Class Main cans f public static wid main (Shing ang f Dog ‘al = new Dog ls Av wok C)5 ys} pas ® Compa asd conrlast irocthed over loading 4 method overriding with an. crample “Ppygy. [ Methool Overbanding |e Defies Definition ; | with Shy sare narne but diPfevem) -pasaretos WUhiN sams claw Methooh must lifter io | the narnber on type of parameters Parra eles Pekan Ty Cam have atfRacl ete | types, bat | L mast Tnherytance | axareter fist | hfe TPesolved ot Compile tie Catatie bincking] 1 Achteves compile ~ firme Polggrocephism Methed Overloacling alas calecclator f public tnt add Cnt atu ate’, y Puxtepe Purpose voaltiple recthads) Not dependest on inberitana [blo parent + child Method Owewsiding * Rede Ging a encttedl Ina. subclass thet is aluady defined tn the parent claws a The -reethed in the Subclass must have | +Ehe sarme signehie Grane, reluirs) as 10 Poxent class _ © Return type rest be the Sarne or Cova iant & Requires 4m heritane lame. Resolved at wustime we Aebtees reotinic Polymorphism eek bf ho Cramp mt add Cint bs inte SEM Ok bee 5 Bf Method Orerviching Class “Animal : Pablic void sound Of Sytem out. priotln CAnimoal”) 5 y J Class Dog emterch rintroal { ” @overide ~ ‘ Public wid sound Of 5 System. ocel print, C&O’) 3 © what” a is dynamic method dispatch? Wlvite a staple Mple that: Uustales dypamic meted Aispatch. coh, DYPOME method dispatch is the mechaniom 6 eh a call 4y an overviden methed if teSo\ved ot Tan me, rather than compile time. i Dynami method dispateb is important because is is how java implements run-time poly rerplise Examples A Dynamic Method Dispatch’ class A wid ca(lme O Syctern. oat spindles Ctoitdle *'s wnctted) i _ a poe 2 a class B extends A { MW ooverside calhene O word cathmeO Sytem out. pantin CPaide FS retool } j Tolaes Centon AL Monerride callrne) wid calle of } Sytem, out. printin Garde CS method class Dispatch { a public slafe wid main stung ag lD{ A az newAl)s B b= new BO ce shew CCF Arts wens + calle C)5 . aeby . | a caller Ys Tee% we -cabllme C)5 7 J 4olp Tenide A's enetheed Tmide Bs methed Trvide C's method - ® What 4S oan svherface Beef ly enplain gens Prem of twleckeee Crys] {An Interface in java is 2 blueprint ofa class. It has static constants and abstract methods. ‘The interface in java is a mechaniam to achieve abstraction. Thera con be only abstract metiiods in the java Interface not method body. Its used to achieve abstraction and multiple Inheritance in Java. Java Interface also represents IS-A relationship. Tt cannot be Instantiated just Ike abstract ciass. In other words, Inerfece fields are publi, static and fal by default, and methods are public and abstract. interface Pritablet interface Printabieg ina ‘publi stati fn int MM void print) uiblic abstract vors ora): ) ‘ Paani aa Presse cans ‘Understanding relationship between classes and interiinces less intartsce Inrartace = css im interface An interface is defined naueh tike « class. "This is the general form of an interface: access interface sare # ype fia arnewne't = exter: {pe fino crnam? = waiues ype fined-varhameN — values returs-ipe wretiod-namel parameterlist): returietype miethod-name2(parameter-list): returactype method-nameN (parameter: i); ‘ycodein 1BCS306A (OBJECT ORIENTED PROGRAMMING WITELIAVA) Java Interface Example interface printable{ int x=100; void print); ) class A6 implements prinsable{ public void printt ‘[Link] printin("Hetlo”); 1 public static void main(String args{D}{ AG obj = new A6(); obj. print 1 objc++; cannot change the value uf the x because i is final | a @ Build a Jara prpare ee ee et ‘Shape’ » Grocle 3 sub classes namely civele, toiorgk and squt > each class bas 2 methed nameal craw () erose O + Demnorttiate Polymoxphism concephe by — cleve loping suitable methods & main program. age Shape 5 . Poetic class shape { of plic void dae OL Copgaaing a hapa sys been i york exase (Of ntlp (Easing 2% shape» } public : Systero- ont Pr Circle . eaters shoe { public void dro Systems out. pantin class CDrowing o Crtcle ”) i Wyte void erore C) Sycm out. print class ee extench ah {c+ Bvcaing a cnc) es pubtic wid draw ©) 3 Systeresnect paints Eraniry 9 D495 : o-— Bens st re pudlic wid exase Ox System -oul-prietlo C'Erasing @ aM ye . class squcwe extend Shape { public wid dvaw(){ System. ood print, C Drawing } shuns’); public wid evase C) Sgptero. out prints C{ Exasing sue) y 5 public class Mase{ public state wid main(shirg lJ cg) Shape citcle = pee ccs Shape Triangle = new Tray le; Shape Square = mee Square + Civeles dao O% Circles exase CD45 taiangles draot)3 ctianale « erase (4 Square « drove C3 + Square: tase (5 Abstract Classes: There ave situations in which you will want to define @ super-elass that declares the sinacture of a given abstraction without providing a complete implementation of every method, ‘That is, sometimes you will want to create a super-class that only defines a generalized foren that ‘will be shared by all ofits subclasses, leaving it to each suaclass to Sill in the details. To declere an abstract method, use this general form: abstract ape name(parameter-tist: As you can see, ‘+ no method body is present. ‘+ Any class that contains one or more abstract methodis must also be declared abstract. To declare class abstract, you simply use the abstract keyword in front of the class ‘keyword atthe beginning of the class decir There can be no objects of an abstract elas. That i, an abstract class eapnot he directly instantiated with the mew operator. Such objecis would be useless, because an abstract lags is nov fully defined, vtucodein BC$306A(OBJECT ORIENTED PROGRAMMING WITH JAVA) 17 Using abstract methods and classes. abstract class Figure { double diml; ouible dim2; Figure(double a, double b) { diml = a; dim abstract double areas. area fs now an abstract method } class Rectangle extends Figure ( Rectangle(double 2, double b) { stperta, b), b Joverride arca for rectangle double areat) { ‘System,outprintin("Inside Area for Rectangle." return diml * dim; } class Triangle extends Figure { “Triangle(double a, double b) { ‘super(a, 9); t double areat) { [Link]( "Inside Area for Triangle, return diml * dim? /2; J class AbstractAreas { public static void main(String args[) { Figure f= aew Figure(10, 10); 1 legal now Rectangle r= new Rectangle, 5); ‘Triangle t~ new Triangle(10, 8); Figure figref; J) this is OK, no object is ereated figref =r; [Link]¢"Arca is" + figrefarea()); figref=t [Link]("Area is" + figrefarenQ); } Dene

You might also like