INHERITANCE NOTES (1)
INHERITANCE NOTES (1)
1INHERI
TANCE
Inherit
ance ist he mechanism injava by which one cl ass i
sal l
ow to
inheri
tt hef eat
ures( f
iel
dsandmet hods)ofanothercl ass.I tisprocessof
derivi
ng a new cl ass fr
om an existi
ng cl
ass.A cl ass thatisi nheri
ted i
s
caled a super
l class and the cl
ass that does t
he i nherit
ing is call
ed a
subclass. Inheri
tance represent
st he IS-A rel
ationship, also known as
parent-chil
dr e-lati
onship.Thekeywor dusedforinher i
tancei sextends.
Synt
ax:
cl
assSubcl
ass-
nameext
endsSuper
class-
name
{
/
/met
hodsandf
iel
ds
}
Her
e,theext
endskeywordi
ndicat
est
hatwear
ecr
eat
inganew cl
ass
t
hatderi
vesf
rom anexi
sti
ngcl
ass.
Note:Theconst
ruct
orsoft
hesuper
classar
eneveri
nher
itedbyt
he
subcl
ass
Advant
agesofI
nher
itance:
Codereusabili
ty-publ
icmet
hodsofbasecl
asscanber
eusedi
n
deri
vedclasses
Datahi
ding–pr
ivat
edat
aofbasecl
asscannotbeal
ter
edbyder
ived
cl
ass
Overri
ding--Wit
hinher
itance,wewil
lbeabletoover
ridet
he
methodsoft hebaseclassintheder
ivedcl
ass
TypesofInheri
tance:
I
nher
itancecanbeofanyonef
oll
owi
ngt
ypes
1.Si
ngl
einher
itance(
Onl
yonesuper
class)
2.Mul
ti
plei
nher
itance(
Sever
alsupercl
asses)
3.Hi
erar
chi
cali
nher
itance(
Onesuper
class,manysubcl
asses)
4.Mul
ti
leveli
nher
itance(
Der
ivedf
rom ader
ivedcl
ass)
5.Hybri
dInher i
tance(
Combi
nati
onoftwoinherit
ances)
Mult
ipl
einheri
tancecannotbeuseddi
rect
lyi
nj ava.Thi
sconcepti
s
i
mplementedby
i
nterf
aceconceptsinjava
Singlei nher i
tance
Themet hodofi nheriti
ngt heproperti
esfr
om onesupercl
asstoonesubcl
assi
s
calledsi ngle
inheritance.
Itconsi stsofonebasecl assandoneder i
vedcl
ass.
Exampl epr ogram1:Si ngleinheri
tance
classRoom / /
basecl ass
{
intl
engt h,breadt h;
Room( intx,i
nty)
{
length=x;
breadt h=y;
}
intar ea()
{
return( l
engt h*br eadth);
}
}
classBedr oom ext endsRoom / /deri
vedcl
assusi
ngbaseclassnamedRoom
{
i
nthei ght ;
Bedr oom( i
ntx,inty,intz)
{
super (x,y);
height =z;
}
intvol ume( )
{
Ret urn(length*breadth*height);
}
}
classsinglei
nher i
tance
{
publ i
cst ati
cvoi dmai n(Stri
ngar s[])
{
Bedr oom r oom1=new Bedr oom( 14,
12, 10)
;
intar ea1=r oom1. ar
ea() ;
intvol ume1=r oom1. volume( );
Syst em. out.pr
intl
n(“Area1=“ +area1) ;
Syst em. out.pr
intl
n(“Volume1=“ +vol ume1) ;
}
}
Out put :
Ar ea1=168
Volume1=1680
Mul
ti
levelInheri
tance
Ageneralnecessi
tyinobj
ector
ient
edpr
ogr
ammi
ngi
stheuseofader
ivedcl
ass
asasuperclass.
Hi
erar
chi
cali
nher
itance
ClassAisasupercl assofbot
hclassBandcl
assCi.eonesuperclasshasmany
subclasses.
Somef eaturesofonelevelar
esharedbymanylowerl
evelcases
Exampl
e:
cl
assShape{
i
nta=10,
b=20;
}
cl
assRect
angl
eext
ends
Shape{publ
icvoi
d
r
ect
Area(
){
Syst
em.
out
.pr
int
ln(
“Rect
angl
eAr
ea:
”+(
a*b)
);
}
}
cl
assTr
iangl
eext
ends
Shape{publ
icvoi
d
t
riAr
ea(
){
Syst
em.
out
.pr
int
ln(
“Tr
iangl
eAr
ea:
”+(
0.5*a*b)
);
}
}
publ
iccl
assMai
n
{
publ
icst
ati
cvoi
dmai
n(St
ring[
]
ar
gs){Rect
angl
eobj
=new
Rect
angl
e()
;
obj
.rect
Area(
);
Tr
iangl
eobj
1=new Tr
iangl
e()
;
obj
1.t
riAr
ea(
);
}
}
Sampl
eOut
put
:
Rect
angl
e
Ar
ea:
200Tr
iangl
e
Ar
ea:
100.
0
Mul
ti
plei
nher
itance
J
avadoesnotal
low mul
ti
plei
nher
itance:
Tor
educet
hecompl
exi
tyandsi
mpl
if
ythel
anguage
Toavoi
dtheambi
gui
tycausedbymul
ti
plei
nher
itance
Forexampl e,Consideracl
assCder i
vedfrom twobasecl
assesAand
B.ClassC inherit
sAandB f eatur
es.IfAandBhaveamet hodwit
h
same signature,there wi
llbe ambiguit
yt o cal
lmethod ofA orB
cl
ass.Itwillresul
tincompiletimeerror.
cl
assA{
voi
dmsg(
){Syst
em.
out
.pr
int
ln(
“Cl
assA”
);}
}
cl
assB{
voi
dmsg(
){Syst
em.
out
.pr
int
ln(
“Cl
assB“
);}
}
cl
assC ext
endsA,
B{/
/suppose i
f
i
t wer
e Publ
ic St
ati
c voi
d
mai
n(St
ring ar
gs[
]){ C obj
=new
C(
);
obj
.msg(
);/
/Now whi
chmsg(
)met
hodwoul
dbei
nvoked?
}
}
Sampl
eOut
put
:
Compi
let
imeer
ror
AccessCont
roli
nInher
itance
Thef
oll
owi
ngr
ulesf
ori
nher
itedmet
hodsar
eenf
orced−
Var
iabl
esdeclaredpubl
icorpr
otect
edi
nasuper
classar
einher
itabl
e
i
nsubclasses.
Var
iabl
esorMethodsdecl
aredpr
ivat
einasuper
classar
enot
i
nheri
tedatal
l.
Methodsdeclar
edpubl
ici
nasuper
classal
somustbepubl
ici
nal
l
subcl
asses.
Methodsdecl
aredprotect
edinasupercl
assmustei
therbepr
otect
ed
orpubli
cinsubcl
asses;theycannotbepri
vat
e.
Foll
owingprogram il
lust
rat
eshow t
hef
unct
ionsofasubcl
asscandi
rect
ly
accessaprotected
memberoft hebasecl ass
USI
NG SUPER
Thesuperkeywor drefer
stoimmedi ateparentcl
assobject.Whenever
youcreatet
hein-stanceofsubcl
ass,ani nst
anceofpar
entclassi
screated
i
mpli
citl
ywhichisr
eferredbysuperreferencevari
abl
e.
Itcanbeusedtoreferi
mmediat
eparentcl
assi
nst
ancevar
iabl
e
whenbothparentandchil
dcl
asshavememberwithsamename
Itcanbeusedt oinvokeimmedi
atepar
entcl
assmet
hodwhenchi
ld
classhasover
riddenthatmet
hod.
super
()canbeusedt
oinvokei
mmedi
atepar
entcl
assconst
ruct
or.
Useofsuperwithvari
ables:
Whenbot hpar
entandchi l
dclasshavememberwit
hsamename,wecanuse
superkey-wordtoaccessmemberofparentcl
ass.
ASubcl assconstructorisusedtobui l
dtheinstancevariablesofboththe
subclassandt he
super class.
Keywor dsuperi susedsubjecttot hesubsequentcondit
ions.
1.”Super ”mayonl ybeusedwi thinasubclassconstr
uctormet hod.
2.Thecal ltosuperclassconstructormustshow ast hefirstst
atementinsidet
he
subclass
constr uctor
.
3.Thepar ametersint hesuperclassmustequalt otheor derandtypeoft he
instance
variabledecl ar
edint hebaseclass
cl
assAni mal
{
Animal()
{
System. out.pri
ntl
n("animaliscr
eated");
}
}
cl
assDogext endsAni mal{
Dog( )
{
super();
System. out.pri
ntl
n("dogiscreated"
);
}
}
cl
assTest Super 3{
publi
cst ati
cvoi dmai n(St
ringar
gs[]){
Dogd=new Dog( );
}
}
Output :
animaliscr eated
dogiscr eated
Exampl
e:
cl
assSuper
Cls
{
i
ntx= 20;
}
/
*subcl
assSubCl
sext
endi
ng
Super
Cls*/cl
assSubCl
sext
ends
Super
Cls
{
i
ntx= 80;
voi
ddi
spl
ay(
)
{
Syst
em.
out
.pr
int
ln(
“SuperCl
assx:“+ super
.x)
;//
pri
ntxofsuper
cl
assSyst
em.
out
.pr
int
ln(
“SubCl
assx:“+ x)
;//
pri
ntxofsubcl
ass
}
}
/
*Dr
iverpr
ogr
am t
o
t
est*/cl
assMai
n
{
publ
icst
ati
cvoi
dmai
n(St
ring[
]ar
gs)
{
SubCl
sobj= new
SubCl
s()
;obj
.di
spl
ay(
);
}
}
Sampl
eOut
put
:
SuperCl
assx:20
SubCl
assx:80
2.
2 ORDEROFCONSTRUCTORI
NVOCATI
ON
Const
ruct
orsar
einvokedi
ntheor
deroft
hei
rder
ivat
ion
Ifa subcl ass construct
or does notexpl ici
tl
yi nvoke a super
class
const
r uctor usi ng super (
)i n the first li
ne, the Java compi l
er
automat icallyinsert
sa cal lt
ot he no-ar gumentconst r
uctoroft he
superclass. I ft he super cl
ass does not have a no- ar
gument
const
r uctor ,i
twi l
lgenerateacompi le-
timeer ror
.
Exampl
e:
cl
assA
{
A(
){
Syst
em.
out
.pr
int
ln(
“A’
sConst
ruct
or”
);
}
}
/
*subcl
assBext
endi
ngA
*/cl
assBext
endsA
{
B(
){
super
();
Syst
em.
out
.pr
int
ln(
“B’
sConst
ruct
or”
);
}
}
/
*subcl
assCext
endi
ngB
*/cl
assCext
endsB{
C(
){
super
();
Syst
em.
out
.pr
int
ln(
“C’
sConst
ruct
or”
);
}
}
/
*Dr
iverpr
ogr
am t
o
t
est*/cl
assMai
n
{
publ
icst
ati
cvoi
dmai
n(St
ring[
]ar
gs)
{
Cobj= new C(
);
}
}
Sampl
eOut
put
:
A’
s
Const
ruct
or
B’
s
Const
ruct
or
C’
s
Const
ruct
or
I
nvoki
ngSuper
classPar
amet
eri
zedConst
ruct
or
Tocallpar
ameter
izedconst
ruct
orofsuper
class,wemustuset
hesuper
keywordasshown
bel
ow.
Synt
ax:
super
(val
ue)
;
Exampl
e:
cl
ass
Super
Cls{i
ntx;
Super
Cls(
int
x)
{
t
his.
x=x; /t
/ hi
sref
erst
ocur
renti
nvoki
ngobj
ect
}
}
cl
assSubCl
sext
ends
Super
Cls{i
nty;
SubCl
s(i
ntx,
inty)
{
super
(x)
; /
/invoki
ngpar
amet
eri
zedconst
ruct
orof
super
classt
his.
y=y;
}
publ
icvoi
d
di
spl
ay(
){Syst
em.
out
.pr
int
ln(
“x:
“
+x+”y:“
+y)
;
}
}
publ
iccl
assMai
n
{
publ
icst
ati
cvoi
dmai
n(St
ring[
]
ar
gs){SubCl
sobj
=new
SubCl
s(10,
20)
;obj
.di
spl
ay(
);
}
}
Sampl
eOut
put
:
x:10y:20
The pr ogram contains a superclass and a subcl ass, wher
e t he
superclasscontai
nsapar am-eter
izedconstruct
orwhi chacceptsainteger
value, and we used t he super keywordt oi nvoke the parameter
ized
constructorofthesuperclass.