8Java final keyw-WPS Office
8Java final keyw-WPS Office
afi
nal
key
wor
d
I
nthi
stut
ori
al,
wewi
l
llear
naboutJav
afi
nal
var
iabl
es,
met
hodsandcl
asseswi
thexampl
es.
InJav
a,t
hefinal
key
wor
disusedt
odenot
econst
ant
s.I
tcanbeusedwi
thv
ari
abl
es,
met
hods,
andcl
asses.
Onceanyent
it
y(v
ari
abl
e,met
hodorcl
ass)i
sdecl
aredf
inal
,i
tcanbeassi
gnedonl
yonce.That
i
s,
t
hef
inal
var
iabl
ecannotber
eini
ti
ali
zedwi
thanot
herv
alue
t
hef
inal
met
hodcannotbeov
err
idden
t
hef
inal
classcannotbeext
ended
1.Jav
afi
nal
Var
iabl
e
I
nJav
a,wecannotchanget
hev
alueofaf
inal
var
iabl
e.Forexampl
e,
cl
assMai
n{
publ
i
cst
ati
cvoi
dmai
n(St
ri
ng[
]ar
gs){
/
/cr
eat
eaf
inal
var
iabl
e
f
inal
intAGE=32;
/
/tr
ytochanget
hef
inal
var
iabl
e
AGE=45;
Sy
stem.
out
.pr
int
ln(
"Age:
"+AGE)
;
}
}
RunCode
I
ntheabov
eprogram,wehavecr
eat
edaf
inal
var
iabl
enamedage.Andwehav
etr
iedt
ochange
t
heval
ueofthefi
nalv
ari
abl
e.
Whenwer
unt
hepr
ogr
am,
wewi
l
lgetacompi
l
ati
oner
rorwi
tht
hef
oll
owi
ngmessage.
cannotassi
gnav
aluet
ofi
nal
var
iabl
eAGE
AGE=45;
Not
e:I
tisr
ecommendedt
ouseupper
caset
odecl
aref
inal
var
iabl
esi
nJav
a.
2.Jav
afi
nal
Met
hod
Bef
orey oul
ear
naboutf
inal
met
hodsandf
inal
classes,
makesur
eyouknowaboutt
heJav
a
I
nheri
tance.
I
nJav
a,t
hef
inal
met
hodcannotbeov
err
iddenbyt
hechi
l
dcl
ass.Forexampl
e,
cl
assFi
nal
Demo{
/
/cr
eat
eaf
inal
met
hod
publ
i
cfi
nal
voi
ddi
spl
ay(
){
Sy
stem.
out
.pr
int
ln(
"Thi
sisaf
inal
met
hod.
")
;
cl
assMai
next
endsFi
nal
Demo{
/
/tr
ytoov
err
idef
inal
met
hod
publ
i
cfi
nal
voi
ddi
spl
ay(
){
Sy
stem.
out
.pr
int
ln(
"Thef
inal
met
hodi
sov
err
idden.
")
;
publ
i
cst
ati
cvoi
dmai
n(St
ri
ng[
]ar
gs){
Mai
nobj
=newMai
n()
;
obj
.di
spl
ay(
);
RunCode
Intheaboveexampl
e,wehavecreat
edafi
nalmet
hodnameddi
spl
ay(
)insi
det
heFi
nal
Demo
class.Her
e,t
heMainclassi
nher
it
stheFi
nal
Democlass.
Wehavetr
iedtooverr
idet
hefi
nalmet
hodintheMaincl
ass.Whenwer
unt
hepr
ogr
am,
wewi
l
l
getacompil
ati
onerr
orwit
hthefol
l
owingmessage.
di
spl
ay(
)inMai
ncannotov
err
idedi
spl
ay(
)inFi
nal
Demo
publ
i
cfi
nal
voi
ddi
spl
ay(
){
ov
err
iddenmet
hodi
sfi
nal
3.Jav
afi
nal
Class
I
nJav
a,t
hef
inal
classcannotbei
nher
it
edbyanot
hercl
ass.Forexampl
e,
/
/cr
eat
eaf
inal
class
f
inal
classFi
nal
Class{
publ
i
cvoi
ddi
spl
ay(
){
Sy
stem.
out
.pr
int
ln(
"Thi
sisaf
inal
met
hod.
")
;
/
/tr
ytoext
endt
hef
inal
class
cl
assMai
next
endsFi
nal
Class{
publ
i
cvoi
ddi
spl
ay(
){
Sy
stem.
out
.pr
int
ln(
"Thef
inal
met
hodi
sov
err
idden.
")
;
publ
i
cst
ati
cvoi
dmai
n(St
ri
ng[
]ar
gs){
Mai
nobj
=newMai
n()
;
obj
.di
spl
ay(
);
RunCode
I
ntheabov
eexample,wehavecreatedafi
nal
classnamedFi
nal
Class.Her
e,wehav
etr
iedt
o
i
nher
itt
hefi
nal
classbytheMainclass.
Whenwer
unt
hepr
ogr
am,
wewi
l
lgetacompi
l
ati
oner
rorwi
tht
hef
oll
owi
ngmessage.
cannoti
nher
itf
rom f
inal
Final
Class
cl
assMai
next
endsFi
nal
Class{