0% found this document useful (0 votes)
116 views

Java Unit 2 R23

Uploaded by

maneeshgopisetty
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
116 views

Java Unit 2 R23

Uploaded by

maneeshgopisetty
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

<br> <br>

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

TAcestngprvate members. gf class class hame


S:
Final
lass and Methods. clas creationde clatien
só iooiavy) hodfn
|4 Construdor
Overloaded
methods for
const rucor
clods class dassname Lhoit
|lo
|llt
methodsounesss
Nested classes
Basing argume nts by valae
Na ond by refetene 2id
|3
13
Abt his' keyword class
class object lassteorm| person
2 Methods 22)
2243 Vehicle Cof Data Mame
fraits Agc
Jntroduction aypes memte
Attibate Rol-No hottst
pecsn Methods Yead
Raju
|2- Defining Methods
|3 Overloede d methods!
Over loaded construta imethods class Rertarg le u ä Ret De moo - 22a3
-
|s class object
, -as, parameters in mettods Juble stati weid
it
int
length)
bíeoth;
6ACtesS Cosro l.
Recursive mehAli int areal) Rectagk obje r ecargle)
|
obj
Nestng tmethods Veturn ergth beysi tate leng
l
beašt he 2j di,
4'ouer riding metho d.ss4 ob-
S yste m'out print!nArear
kottribtes and statieon dtyol ac
tobj are )J;
3
to
<br>

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

These Va (iables afe Sco local in


2 areal))
ob Sco
and ot acce
ssablectsibe ths, So
2 class yatioble
s331
Decatation of class object The se Narables are alsoquaige d as smstatii:
name O; Vogiobla Malae these
= new chss The of Varcables a Ye
lass ame obiectname
Conman all the objecs af the
thase vánib
2. as (efeten e 3
The class Copy
All
nane' the abjects share he Sane
narme Obje ct
ikis class
class sample

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

ctass' Sanple Oemo


statie void main (sting args(1){
C
onstrut
ime
initialang
e object
object of the claus

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

Sytem out print Ancbe"tobj-b); default const


Sample c factor:. doe s not
t any
Constuctor which
Sys temout pirtAnd= "4d); scejt Jafa neter.

1 alameterized Constractor : Con strucior which accept

ang aameter
Consttactos
<br> <br>

Dtault hoRarameterized Constractor Overloaded1 Constuctor. methods

class kectonge class Rectorngle poiln


more than
Constructor with
ina
length, breadthy 2 patamettrs
int kength,bíeadth; nn int Same,class wth different cal
Rectonglec) boolbectangle (int x, (nt y) Constructor oueióaded. method

systemat pinttn ('oefat Rectangle


breadth =j new
ntw Rectngle ( toj ko);
V Rectangle
Rectangle
r2eznew
breat th r3 Rectangie (30
lo;ot) eont
Tect Are al ) Reetanglere
ru =
int new
pmsfs s
int rectAreal)) reta(n ( length* beadth);
Lrogcam
retun (length x bre oth) ;
class Retangle
clacs Rectangle Derno
Iength cadth
class Recarge Demo mainltring Rectongle
Jublie sttic Void
)
{ Systemout- pinthn Area
Defaut double TectAete )
statie void main (sting 3s"engthlo? Construter"
elic Retengle(ig
{
Rectangle8e ienew et
fectgle r:
Aength *braodhy
rintn"rere a g
ne
6ystem out
"
syte ud pntin Aea of
ectangle *
trl. ctAea) Rectang'e (doubk xà ouble' )iOssrhisJ
rectargl *rfectArcal)); Syten odt- prnttn ('paamterized
Constut);
length=x;
eadth = y;
dton
Rect an gle(double z)

length s;
bre ath:Zj
<br> <br>

class Rectangle Demo

publie statie vod


Void.main (String ars(1) watige
Sytem out pint n Ad;trönà"+at blhe
Rectangle Re ctangiel
Reckongle
class
Rectange
ThisExam
ple)pts/
Retange (i2);,
yuble state void moin(string argL
Syten ot- entAn
Aeat. eckange2s torrect Area);
Syatem out printtn ofAen
ectangle='*r3 ket Area)
obj -add
double rectl, rect rect 3,

Yectle rl. Veaf Arcal;


Yect * J'inal class and
nrect. Areac); Methods
rect3= f3 rect A(eals;
Systetm'ot;intnl c hon b'access' modifiers
m
usedto
System otprintAn
T
he nal ReyoKd iistoa
Systeimdutrintkn3 rect J; classes, attributes (vafia blesd k ethodsd;Thatt means.
cons tant.
it makes them chgable (
Reqword this
2- The final Reyoard is used ways:
In
The tayuotd is teference varia ble Jrovides
2shivo
2- Metheds
rejerence to the Current object 3
classes
Final variable: you Variable as
If make we
.
t: class This Oemo
Cont thange the lalue of final vuble (eongtant
Nay}
int ab; Roqyom
set a
Void Valae (nt ,int h) dass Final Demo

final int aalo;


this a =4, pabtie
sttie void main(stmg argst)
class as
<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)

Sgote mad rintko


ramng safely ath lo
public satte void
- Member
rmainstr inner
pubic statie woid main (st ing gsc
hew stHO;
2-, Anod class
SSsS•veadc =
3
local class
Honda( y stttc?Nésted class
Honda heew
h run )

ole
over ride becoz it is
Tan in Honda class Cant
a
assigred with ftral
<br>

Access control 4or clacsmembe rs':"


<br>

Aecess moditiers, .. for methods

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 :

Any method the


any lass cah aCcess ghen meod iš said to be protected inside a cla
mehed inheritane
it wil be acces sable ftom ts sab cas
) rotected class erert
in the Sa he ackage only
inside a class
t
a
oill
varioble
be
said
acce ssable
to
fom
pestectet
ts
s
subclass
2
Defre in the Same class feent Jaceage oly
via. inhertonce defihe prae t ol be.ace csable
Pitei uith in the clas it ii defired Such as

Nariables aYe not


ony within deftre de such
Jeom the class, t is,
he 'lass ot eveñ
its Sub clas
Nafiades ae ot accetsables fron outside

deghe class not en it


even Sub cass
<br> <br>

þublle Access rivote ACcess Pdected Defaut Tpes oj


visality modifes
Nested class
within the Yes yes Yes
Sarne class Yes
Inner Non-statre stati c
Yes
Westel dass Nested cbs
fromAny class yes No yes
in Sare )Member Jnnerclaas
b)Local Tnnerc las s
fom Any Sabcass Yes Ves
2 yes )Anonymous Tnnerclass
in Same pocRage

Yes Conly Non


From Ang sabclass stati ested ass
yes No by Jnrestane
fom aee nt jctag

ron- class
also called
anNg- sub No
fom 2- Jhner cass )u tostth
mo

jron ditjerent dadind inside


dayired * anohe inner class
a)Membe r Snner
class. Aaswhich is declared
dideNested 'elass as mernberb, wthin: andher class
hother
such
member 22 is called
iN
define a'cassoth Jnner class
ht
called Slax:.
class is
pesicklass
- outerclacss
Syntax class
code
Ne sted class qblic clas
class innef closs
class
Jvale
otete

Types o Neted class.


CJass Oter
there afe tuo tyyes of Nested class
e
irt lenghi
|' Non-statie sted clacs int wth;
2
stti Nested class Outer (int aitt b)
length a;
<br> <br>

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

void inne, displayc) anonymus das ik deftned by an o perdt ir


Sycte out-prirtda"Area4 area")
2- his class Can be inplermented with abstract clau
erhes
class Nested Demo
statie bid main (Aung
blie
abstact lass Poron ) sy bi

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>

Local inner class (or) Mehod Local das


sttic
cass de clared in a blocle the
chss f use
block. ;To, a nested
Stoe he lacs isinted tohe declae n,
sie
SsC
2- The aCCesS modifiets ublie piater otet a
stotic keywoe 22935

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

public static void mairn (sting args() Cannst declae

class Local 2) doss outer ogtan

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

Local obj : new Locol (1o


int ofea)
Ianer ine ne Ihner();
obj disgaycO;
in fnne-Displa
yj
skat votd
class LocalDemo oterdeyay
vod maip(tring Inner in= new Inner();
args) in innet-èislayty
oter obje
hew oute(l
q°bjoute-Puplayly
<br>

stdic - rrodifer <br>

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

int ab; PsUncstring agsí void displayl


Void setValues (it.int
{ obj= new Sua) So-P CIn Suap clas: atat b:b}
Suap
aP
x=x,
3 So-Rinl'Be jore suag
void sua pping €
class {tcal ByReferenceo bois
ob' setvalucs (x9) te
int tern; obj sujping
=
tenp a (e Sua obj
ne
Suap;
a b; sön(er suig ob a=lo;

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,

they inlude the blbuiny.


behayiour of an object

Defning 2-Types Jaametets


3 They
f
order in the pAaneter kst t
Modifier ypem"method ameC )
{
e xamples
void methodll)ibots
2 Void nethod ( it
3 void methodi (int nint )t
roqrarm
melhd (int nint m, int P)
class add method \ (doiuble x, double y)

int acbj int Surn(int x,int y) biov


void set value s (int x,int y)
class 6verloadedMethod
hents Mit keb;
atb; {
Tetuin ; method )
Void
tl
Sum)
Sam atb)l S.0-PAoNo walue to etun
turn, at b;/5oPAnc
i soe void methodl nt n) so'Plnc Sabsttactton: 4(*-);

at9
pablic stahie Void mainGting argDon Class
Ouerloaded Oemo

void methodl (int n


int mAs(string:emá
A&"6b'new Addl); Methid obj=new
wtáo obj-set valu,es (lor2o) os
). S0-An ( Addition "(m)overlosded 2:eoverlodad Helt

hoolsso-rAnc'sum"
Su
obi-method 1(2o8oJ

obj method l(o-2, oi


<br>

overloa ded Constuctor Methods


Construçtor within <br>

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

Void aáC) bs obi;


An ("addition "4atb)
Sgtem out pint
Methods
<br> <br>

class- cbject as parameter in Kecursiveethode 2L

as parametrs to itself is calle d


object can be ased The! method1caling
by

the methods typeofthe obiect f Ye cursive method


the 9

the class class, er: )Factorial


the Darne
it IS Called call by refeene fact nfact (n
IKogsam
sact e u
*jact (3)
Add beno
Demo fact 3 s y*3*oct 2
) class class
Swop itso ) Jact *
3* 2* factl
obj
yact *3*2*|
int abj void sd& (Adt
Qomo
void Sioap(Suoot obj
class Fact Exam
abbjla; class Factc -
publie ctatic
vord main (steng
argo

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

obi displåy ), a b); 44


Sunppiny ta+'be"
S'6Lntef
<br>

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

ca ss Fibtxa obj ew A(O;

joblie stati hid main (stang argsD obj hello;

for(int i-l; ic lo;it4) 2) cass Nestingetod


class
int afb} veid
pabie static Void main

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)

S-o-Plncthis is hai method;

Void helloc
is hello metho ;
So-in cThis
welcome (;

You might also like