Java Unit 2 R23
Java Unit 2 R23
O
nty 21
( class: elass is
cdlection of objects
classes ond obiects' logical entity
Int roduction
2 class declaration and modifers
3 class memberfs 2xms
r declaration o class obie ct Sytay for
Acsighing One object to andter
object creation:
6ccess Cortal for cass menbe
dhother
<br>
one obje ct
class Mernbes
body ofa closs
clacs Memes are
decaed ih dhe
We sending Aobieet data to anothe r
These
tnay lComprise fields, methods, nested clas
intesfaces
ofe)
Dermo The types voriable
x: Cass Reclanglel Ret fielas com
pie
uo
tao f
int Aength,;
ubli statie void main (Streg
int breadth; Types variablks statie
int areal) Re ctonglel re 9ikreon-sttir
objle
e breadth; Rec tong el
obj
ehun Lengh
Yetuo
locold Instan ce Varjable
te tContains
cbylengthe loj
obit- Keadthele; objeci
a) Insturnce Variobes These
e ae indiidual to an
Ave a ofobjec:
Systemiout ptln tobioreaJ in the
objec,
aj Coy
o the Variables
objl =objs, memoy
o;
Static intt
pub lie statie doid pmaincstring argec)
nt onstrutor:.
<br> <br>
va viabl.
'Samle obj= new Sample( Jy
E for insfanco
(vafasleed
meábers
mem
system out print Anl a Alee'ss Conttó) claks
(
System 'out dn (
print An 4 Sampleb) Constructor mthodsfor ia
system: o ut
intdnce"); 1: Jayo method calle d Con structor.
sonides scial
2: The class name and he
eshould
constructor name
Sub classes be
03 the Same
class Sample 3 has no feturn tyPe, it does not vetrn ny
int alae
aslo ti even also
int ;
static int e
=soj methd s 4nd
,
t use d to
ulic Cre
attd The
is
Constracor method is ttomatically
ew Sample JimhoyCalled
Sample obj<ct
Constractoroo
2
wthot
Systemo td prin ne a parameterized Con
stractor
ang aameter
Consttactos
<br> <br>
length s;
bre ath:Zj
<br> <br>
jina
final Demoob =
neFinal Demo (O; you mate any
sytem out- rintn"a + obj oJ;ehx: e eend
3
otjas26;
we Cant efckatgk ih class student
I· final cacs Bike tfinal
Sytem ougrintn (' t
Uoid readC)
Void anNC) {
output
to fioal variable
a sopread ing';
0s
valae
obja =2o
studentkits erter
cbss Honda ertends 6ke
class
student
Final Motha ang mnethod as
fnal
mate
you
void roun)R
void rea&)i}
you tant over ride t tog
not read
So-p( Toning sgely" hssop(
h
gib)oien Aáss stadent
stalkvoid main
class 8iRe { read o public.statie, doid mainsting agst public
void
(eiefinal
final voidan) reading" Honda h ne Hortaly stadent kits S=hew stude
Rit)
System oul-pinldn (' tanning extentsstudt
S•readC;
class sH
class Hoda ktends Bite void read ()
not read Vested clses
s"o-C
Void,func)
ole
over ride becoz it is
Tan in Honda class Cant
a
assigred with ftral
<br>
ault:
* Access modifiers Jor variables linstone sttie riableJ oill be
': 21 mehod is aid to defautit
t Default ohich ate defne n tfo
2 Public ccessable to the dass
Sarne Jackae
potected define d in te
which is
in class
a
De ault vafiable s, said to default it will Same JACERgeoj an actess fhecVhvRDbt
method
iyia nheritae
be accessable to deine in the
he dass whichae
Some
)- Rublic :
the
t oll e
method difined in
"Any „.any cacs uhih is be publre
| uhen a metbed iso Sail to
Same Can acC eSS the variabk Via EVa cessa ble with any
nheritence (or) direct
clas
acce sS
2253)
2: Ahy thod in thy dats Can
qcess the given
mthod
via inheritonce.
|when said to be pabie it can be
sldois
3
acce ssable fon any clas. etrded :
ron- class
also called
anNg- sub No
fom 2- Jhner cass )u tostth
mo
it aea()
{ outet method Aronymus clacs
a clacs
etuín deng * width;
Aength deared without natte
object ce ae The inner claSs is
Vod outecdispayl) is called Aronymous inner class
Tnner in =
he
Syntaxi
Ihner);
in inner- dis playly class ome new class name()
cass Jnner
neuw
outer obi
ch outer-displayy abstact void dispayu:d
closs Anonynousemo
2) clacs outer
class nner
stotte Noid main
soid \Tmet display (inic oRerson Pnew
Vid daylay
outer obje ewoter(
vgid oute- displayC
njoter.diszlay(} bis
Seagiihnto
ne u P-desplay
Linne ins Innerc;
in innerdisplayl
<br> <br>
do not
aply local elass pablic , piuter petected
2
St nay be declaad
3 These afe not visi ble ou side the blosk. tmodyer
3• It Can be aCcesse d by an outer lass ame
) lass Outer 22013
int x}
tt stticclass outer stotic class Sner.
vsi à oater-0 splay)
focal (int a) hiou void ihnetbisplay)
closs nne&
are
irrer.Displayl) static oter (nt a rt by
Areat
Void d
isyoy)
So: knHi,I am in Aengtho
Innerelars
Regword : St is
aced tor mainly rremary
i cla ss Yonstatie Petma 1
nangenent
oypicable jar veriahle, int
2 The sttic static, int b=loj
nested classes
methods, blocks ánd statie vod drpay(y
3 be used with
The staic Can
(- Variables
So-pn welcarne to stalc
Method
2- Methods
3
Block void shoo()
b' Nested classes
. SofAn welocone to class Method
Ivariables:
To decare lariable as atat then it is
stati
Called static Variable. 2s
2- static mtho
declate
tmethod wth a static then t
is called sttic method
lass stetExample bodtsi
method"be long: las.to the
2-The
stat
sta
method. inokeswthoutcreattng .en object
{ pallie Static, void main
(stingfgs ()
of the class statieDe mg
sd=ne tc Demoty;
A
is 4sed to initialize st dic cdata memberg Oytemout prt n
B=4static Demo-b; 7h2
before the main method. i*StatteDemo displayc;sini
2-3t is eke cued
<br> <br>
2- (all by reference :-
Passing arquments by ahve k byafeence -the object will be paased
to
Jn Call by eference
-
aigumonts are the methods ohich are dec lare d bsvathei method as agunent,
the akees
tn the methad
poye b Yecicve
be passa
Brogam
AS a
to the
me
thod. olg aments Can classsuapsibod
in two ways int ab;
Vsid
setalues(s wap ob
Call by Nalue 2- all by eferene
asobjla to
lCall by Value. Jn call by alue actual oargoments beobjlbNo,
caped into farmal argutments veid swayping(
Stogtam: - it tem}
tempeaj
c CallByalue
closs Swap lass
Jermal pamles
GYb-teme; 4
void dplay ut
Sytem yntin("oejoe sui"g
SoPAn(In Swap class
: as tat "b:b obj set valaes(obj
obj sayrha
temout
System out ptintAn fter swaing f"bsu.
<br>
Methods
<br>
Dverloaded Methods: -
and sop are
Method:.b Method s name
with the Same natures
dite rent Sg
A method represents ¢n action
actionon data Jpe
fmitted, jrovided,; they have,
at9
pablic stahie Void mainGting argDon Class
Ouerloaded Oemo
hoolsso-rAnc'sum"
Su
obi-method 1(2o8oJ
nalhau
mofe fhan
metev
Yasing abject in consttuctor
class.
w
ith different jata
Same Gh
should sa rne class Rectangle avea( )
narne int
2' cass name Consluclor
it doesn't return any int ,b; retorn l*b;
3
No return tyye
method is atomatialy Retongle
a (onstuctor
of the dass
called henever new object class Oue rconst Method
credted nain (Strrn
publicsstate void
x
Yregiam oyerloa.ded Method Rectongle (int int )
chass i Ad Demo ss2
class
matn(String
Rectangle vhnew ;
Rectomglet
Rectagkb
Pablic static oid b=y} Rectangle lnew
int aib) Rectange ohj3=ngu Rectagle
Aàd
{
Democlhoee Add Demo ab new Add Derol
R (int n) Rectang le oj= new Kectgle
Oa\o; obil addO; (obj
Add Demo obi2 hew A Dem So-PAn¢'Rectlobilaread;
Add Demo(int x, int obj 2 oddlO; Otpdo SoPAncRect `obj2are&;
S
ropdnc Rect obj3afe at
{ Rectangle (Rectangle obi) S'opan c'Rectu' objlaeat
3
S0n"Adition=at int fac torial (int n)
void fact obi. ne factsj
Sooirg)
int temp
class Passo bj Jorlint i;icz6;i)
PSVM(string argsl)) s oPinc'Fatorialobifoctarali
-jatotempa
AdOe mo obileneuw torial (n-):
b=teme) Demd)
wi JsnJac
efurn
void displagL) objl"a= too
hAA
So-fCIn sunp clacs: a=a+btb obj 1-b =2oo)
objl adé Cobj!:
class by call by Rkfeetse
ERonple or fonaci Series
fibn-fib(n-gibln-))
Saap obj rew fb(ol=o
o
fib()=l
bj be lo fih( )|
SRAn Beore Suapig:a tat'btb);o fib( fib(3-) 4fib(3-2)=|tle2
2t\ =3
ob -set valaes (oo) fib (u)fib (u-) tfiblu-)s
Ioglam
<br>
Void weleome()
class fb
bon yesla ,
int ibgacilint So-PAnc weleome method tai)ibboscoh as
y haic ;
veturn n
else
class amaste
return fibonacci(0-04 fiboracei(n-y;te i
D
Jublie stattit wbid main(string argal
ud6
2 a=lb; diry
Nesting of Methods NestingeMethod obj e ne
Meth
So-pincAditton="+ (atb))
anotber mehod in the Same mul
A method caling oasjo pj
class caled
Wes ting of mtheds void mnul()
is bonfsn
azS; b=c;
so-Pncatiplkcafion=4(a*b)
class A
A
Woid haiC)
Void helloc
is hello metho ;
So-in cThis
welcome (;