Java Programming Class Overview
Java Programming Class Overview
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 [Link], 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
[Link](} 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
[Link]) 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: [Link] 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 [Link] 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 (;
Static variables, defined with the keyword 'static', are shared among all instances of a class, meaning they have the same value across all instances. In contrast, non-static or instance variables belong to specific instances of a class, and each object maintains its own copy of these variables . Static variables are initialized only once and can be accessed without creating an instance of the class, whereas non-static variables are initialized each time a class object is created .
Access modifiers in Java define the visibility scope of classes, methods, and variables. 'Public' allows access from any other class, providing no restrictions on where the item can be accessed. 'Protected' allows access within the same package and by subclasses, thus enabling inheritance while protecting data from unrestricted access. The default or package-private access level restricts access to within the same package, providing a more controlled level of access than 'public' but wider than 'private', which is useful for internal API methods and variables that need package-level access but should not be exposed outside .
In 'call by value', copies of the actual parameters are passed to the method, and changes made inside the method do not affect the original variables. This is advantageous because it isolates the called method from changes in the caller's argument, providing a layer of protection for the original data . However, it can be less efficient for large objects because of the overhead of copying. In 'call by reference', references to actual parameters are passed, which allows direct modification of the caller's data. This method is efficient for large data because it avoids copying, but it can lead to side effects where changes in the method affect the caller's variables, making debugging more complex .
A recursive method is one that calls itself within its own codebase to achieve results through repeated execution. This method often simplifies code that would be complex or lengthy if implemented iteratively, such as depth-first search algorithms or factorial calculations . The potential pitfalls include stack overflow errors if the recursion depth exceeds the call stack limit, excessive memory use due to many function calls, and difficult debugging since the execution path can be challenging to follow .
In Java, a method cannot be overridden if it is declared as 'final'. The 'final' keyword prevents changes to the method, ensuring that the behavior defined in the method cannot be modified by any subclass. The practical implications are that it provides assurance about the behavior of a class's key functions and prevents unexpected behavior changes due to overriding, which can be critical in systems requiring reliable and consistent behavior .
Static methods in Java belong to the class rather than instances, meaning they can be called without creating an object of the class. They provide utility functions that are independent of object state, such as mathematical calculations (e.g., Math.sqrt()). However, static methods cannot access instance variables or methods directly, as they are not tied to any particular object instance. This limitation means static methods are best used when functionality is independent of data maintained by instances of the class .
Constructor overloading in Java means having more than one constructor in a class with different parameter lists. This allows a class to be instantiated in different ways. The benefit is that it gives flexibility to object creation, allowing objects to be initialized with a variety of initial states based on the constructor used. Overloading is particularly beneficial for scenarios where objects can be created with or without specific initial data or where different initialization processes are needed depending on the context .
Method overloading in Java is the process of defining multiple methods with the same name but different parameter lists within the same class. This allows the same method to perform different functions depending on the inputs. The significance lies in increased code readability and reusability, as different methods can be called with different types of parameters without confusing the compiler . Method overloading occurs if two methods differ in parameter type or the number of parameters .
The 'final' keyword in Java is used to make a class or a variable unchangeable. When applied to a class, it prevents the class from being subclassed, ensuring that its implementation remains unchanged. For variables, 'final' makes them constants, meaning once assigned, their values cannot be modified. This is useful for defining immutable constants such as mathematical constants or configuration values that should not vary during execution .
A parameterized constructor is a constructor that accepts arguments to initialize an object with specific values. Its utility lies in providing better control over object creation, allowing objects to be initialized with specified initial states at creation time, unlike default constructors that do not allow control over initial values of instance variables . This feature is especially useful in applications where default initialization does not suffice and specific configurations are necessary .