0 ratings 0% found this document useful (0 votes) 8 views 16 pages Java Module 2 Notes
The document discusses object-oriented programming concepts in Java, including class definitions, instance variables, constructors, and method overloading. It explains the use of the 'this' keyword, static members, and the significance of constructors in initializing objects. Additionally, it covers the concept of recursion and the final keyword for defining constants in Java.
AI-enhanced title and description
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here .
Available Formats
Download as PDF or read online on Scribd
Go to previous items Go to next items
Object Ovtenteal Preqramming with Javea Ces so6n's
Module ~ 2
© Tolapet the gerwal form of a class tort
ao example (mary
>The Geel Gem of a class
* The class
* Classes
ts declared by the
can (and usually elo
Corryp lex .
i feomicgh ey [co
class key vooral
Yiget much more
8 A sivophRed
TS shown definite,
Class classname
type instance -
Variable £3 type
frstance — vaviahk 2:
TY pe instance - variable Ny
pe metivdname Cpaiametiy — Got
A bockg of the metwl
type mmethednames (parometer ts DL
\ *
A------ eat
type method rene N Chara meter ~ [5 st)
# The data, ov variables > defined withn io
class
ane called trlance variables
eel es* The ode ts
* The code .
+ Coblechyaly » the methook £ variables defined
within ao glass ase called members of the class,
© The
contained within metho
geneva Bim of a class ‘cloeenot spec!
8 wsatb O) racthod- . . 4
* Java. classes donot ned to have a Main C)
method -
Example Here ts a class called Bow that hay
tthe “three Inetance’ vaviabks with» height ¢
depth > -
class Borbear |
clouble widths
double height 5
double depths
this class declares an object of type Bor
Class Boidemo{ ;
pablic static void vnaio (string lS eng) {|
Bow mybex = neo Rot +
doable vols
a assign verlues to mayboe's inglance van tabke -
Fog bot: caidth = 105 .
roy bor pbegh! 220)
my bos depth =155
T compete volume of box oO ;
vol = imybor width » myber height cp myboxecepths
Sytem spouts print In C8Volame ts” +vol)5
7
Bim
Ductnert .- Valame is 2o00-0@ Discuss the signi cant Featoves of the Bites
ketpootch: [Pye I. I
“hTbis , :
a method tll meet to refs to the ‘object
amehimes: a
rae tevoted tt. To alles this, Tava defres this,
sta Eeyeowrd -
+ Ths can be used imide omy method ty sefer 4, “the
eant object + That is , this is always 2 reference
ty the object 0m Which the method was
invoked
¢
* Boa (double wy doable hy double d)y
this -width =@>
this . height =>
ss depth =ds
Frame
R Thee ae € usage of -this Feqeoord sh java
ry othic can be uscd to aes coer? class
trbance variable -
Ayvote cument claw methed
be asec to
Crmp tei tly]
ny this can
cused to inyote cument class
wy AWS) can be
contbructes -
wy This can be pase“ as an axrgeimersd in the
method call.
‘) This can be passed as an arqument tn the
a confauctos .cal :
used ty _— the
the method.
cumrent clas
Wy this can be
tnidance fem
Deon
dlWy Stake
(+ When) a memba, is decland shake, 4 can he
Accessed be Loce any objects of 4s class ane creed,
and witha aefeenee to any object «
>» You con declare both metheds and vartables 40
‘the static .
* The most common entampk of a state rember
is main CD,
s maint is declared 'as wtate bea th must be
called before any» objects ewist
© Trstance variables declaxed as static are
> essen Bally » globe | veriabhs
# Metheck — clecloved as’ shatic have Severa
* They can only call other Stahe methook
+ They must only aceess Stake data
£ ™ canned vee te This of super in anyeray
eB ple ff wabrade Static yeetab less rnethodk 4
— me Dep blocks
Class Use Static {
state twha =35
Stake. int by,
Static yeid meth Cint a
Systems out printla Co#=" 4x)
Sasters cat. pal istlh (eae? 4a)5
Spier ook pe votle (Ob Les
Vetatief ay wets
Sytem cet: printiy (Static block ti vox
4, oe
publi estate void medn Oshing at DL
meth (49); a
v3 5@ Wheat are concfsuctors 9 Explain hoo types
of conruchys with an cample program CPyg]
* Vaya allouss objects to itntthalize iwc laae
when they ane ceadeds This aufomatic fottaliatc
‘SPefrmed through “the use of 2 Cor
* A comslauctos initializes an object tren edircrtely
APN Creation :
* Doce de Bred tt ty auonatically called when
The object ts created beBee the neo opetorbr
Completes,
ee haw ne vehan types not even
~ HH Two types of Commbuctrs
ty Default Conshuctr
A combsucter that has ne parameters
defauk congiucty . D4 is tnvistble ;
Example - YW Here Boa uses a comtyucte ty intel i
the oltmenions of a bow, = ntbabag
Class Box
double voidth :
double heights :
double depth 5 B=
is known agATS Vs The Constructs far Bow
Berl)
Syyrlero. out pritle CoCorthweting Box’) § wathau,
beight = 103
de pth= lo,
1 compute and ackan volume
double volume Of
Aeten woidth + height + depth %
© al” “class Ba demol
| public static “wid wain (Sting ang Df
Ncleclare , allocate, 4 initialize Box objects.
Bor rogbor | = new Box O3
Box eng bor? = new Fou Os
hole Nol>
iN qe* volume of Basf bow
Vol = roybott+ volume 5
Systems out. print (Volume ts" 4 yl V5
4 get volume of bor
vol = my bow? volume()}
Siyctern- out. printi (oNelume is” aw)
; ; . ou‘When this program is run, it generates the following results:
constructing Box
Constructing Box
volune i¢ 1000.9
Volume 42 1000.0
Parameterized Constructors
Acconsiructor that has parameters is known as parameterized constructor. If we want to initialize
fields of the class with our own values, then we use a parameterized constructor.
For example, the following version of Box cefines a parameterized constructor that sets the dimensions of a box as,
specified by those parameters. Pay special attention to how Box objects are created.
J Here, Box uses a parameterized constructor to initialize the dimensions of a box.?/
clase Box [
Souble width
double height;
double depenr
J/ Ghie is the constructor for Box
Bex (double v, double h, double d) [
width = we
bs
[Type text] Page 14
Jf this is che constructor for Bex
Box (double w, dovble h, doubled) [
width = xz
hesgnt
depeh
'
/f compute and raturn volune
double voluna() ¢
return width * height * depth;
,
?
clase Boxtemo? |
public static void main(string(] args} {
(f daclare, allocate, and initialize Box objects
Box mybax] = new Bow!l0, 20, 15);
Box mybou2 = new B04(3, 6, 5)
double vols
¢f gat volume of first box
vol = myboxt volume ();
[Link]("volume ie "4 vol);
/1 get volume of second box
ol = mybox2 volume ();
[Link]"valume 4s "4 vol};
,
‘The output from this program is shown here:
Vetane sa 2000.9 Geen® Wheat is rocthed overloading * Pustrate the
concept of method over logating using Java Prograr:
(oR) .
Develop a Tava progres +o Find area of nectana|
ava of circle, avea of triangle using method
overacting concept: Call these — methaok” Prony main
method sith settable inputs CPyey.
ey
at
* Overload ng Methects
+ Do jaro. it is Possible te define truco oF more
rocthids “oithin the same class that share the same
mame, if their pevameter declaration are diffwest-
avlhen this is fhe case, the method ore Said +o he
overloaded, amd the process ig. vefenel to as methed
over loacking :
Tow “Pasar Osing Methed Over loadting
public class Avacalculator {
Hf Fos axa of rectangle :
Public double aleulaterrea (double length, double
eodth){
ache length + width 5AMehed to cdleulateAva Kloable ya of! circle -
public double calculaleArer Clouble nadiss){
aeduw Math. PE + aacdius + radius >
e
DMethd do calcuble the aca of txtang!
double caleatatera Couble pase double
height , boolean is Triang |e
setuin 9.5 base # height 3 .
oh an Cstesogt So 5
vk main tg ST Late?
~ public
pablie static
Ancacalcelerter
calle
Mealoulede display “the once of a rectangle -
double nectangls Area = Caleuloctars calculate Area (5-05
sycten vost epintin (Arco of Rectangle: "+ rectangle
3.0) 5
ea)!
of a circle - -
freaC4.0)3
Area)$
We calculate 4 display The ove
double circle*hea = calculates + calculate
System soack- printle (Area of Circle + ” iciacle
and display the avea of a ak
A calealate
double Leieangle fren = calculator: calcu late tea (6.0, 2-5 y tres
Sytem coceh: priot te (Area of Ariangle:” 4 Arian b cre)s
} _odpe® t+ hice of Rectangle: > &
dhea of Cacld 2 60.2652
fren vf Be 2 FB
Qa® Design a class called *Erngloyee” with Belek Pp,
Name and Salary. Write a suitable
contractors 6 methed
+
Taise satary and a Static methok +o disp ta :
The number of Employee objects. Write suitable
Main methed fr itlastetion CPYay.
Class Emplocee
Private. ink td 5
Prvate stay name;
private double salary,
Privake static int emmployecGount = 0 5
Neorstvacto: to initialize Employee Fields .
public Employee Cink ids string name, double salen M
this id= tals i
this - narne = name 5
this . Salary = Salary ; .
einplogeccountrr; #Enevement count for every objec)
bMethed fo saise Salary by a Given pexcenrtage .
pablic void radsSalary Cdoulle percentage )f
fe Cpmcerrlage >) :
salary + =Salasy + percentage /too\s
4 pane gaueeee 5 3.
Jeb}
Sygdem. oct» print lo @ Povalid Revcentaage + Salar
4 ee eine oy JMethod to Aisplay emnployee detoik .
Pbk void — ahisphy Pe taik() f
Systems oul. print [n CODD 4 tol ey Name: “treme”,
\ Sa lary * tsalary 5 aa
MStokic rncthed to display total mofo of ohjects
public Stvke vord clisplay EmployeeCount Of
System « pute printiy CTotal E mplogees + +
er plogeeccurtt) 4
Tain method for dletnoritvertion -
public static yeild main (Shing CY ag )f
[execcke employee objects
= hew ogee Alice’, S000);
Employer empt = hee Emploger Cor, : 5
ple emp = NO Employee (wr, “Bob”, 60000);
“/ Displey
Sytem s out: Prtotlo CsBefse saisiog Salary 9)5
empl disphy —cletai’
empl cisplagDetaih 3
emp? > display detaak Os
11 Reise Seabees y
empl» waiseSa leary Cio)3 / wor).
mpd» AAiSe Salary GB): try1 Digplag ueptakd etait
Soto souk. prinily Cé\n AFfer raising Salerys’);
dame”, emp ofi'splagDedaik();
emp. despl ayDetaih CD;
Vii UT Display cenplogee total cocant ,
Employee » display Fm ployee courst 03
7 J
@ Wee a program to pecfisen Stack operations
using proper class — Methooh CPY8)
# tae is a class called stack that implements
Fe a stack of integers: -
}
Dy 1 Ths class defines an integy stack
hold to values dT SPCR that can
class stack {
ink tek = new int Cis);
ink toss
M itiabze +op- of slack
stact OF
tos =-(5
Wpash an idem onto the Stack
void push Cot tte) fott
if Ctos 2-4) :
Soptem oud. Pent C Stack ts fu);
che
Shek C+ttos}e items
J
i pep an item from the stack
int pop Of
if Ctos £0)
System. cut. printlo (¢ Stack ender flows.”) 5
return 05
eke stct (tes --];
{1 Mean funckon
class Test stact {
ablic stake wid main CS4rin emp Df
Slack roystack £ = new Stact O35
Stack mystackd = pee shack OS
IY push seme numbers onto the stact
for Cnt te03 L103 i++)
maptact V. pashOds
fos Cint tzto4 i £204 t+)
rogptacka push Ci)s
DeenJ pop Those nurnbess off the stack -
j
System: subs penile CStack in m Jacks
fe Gnbico si 2ios tes)
Syter - souks Ps wntln Cenystact - pops
Sapte out Print CStack ty myshet2-D4
Get eo. tte a)
Stptero vou . printto (mystoct 2 pep )3Recursion
Recon’ the proces of ein something termeafis Ae atest ve roaming recurso she
stibute hat sls ametodto calise. A mtodtat caleRets sito be rcs
‘The cen xanol areca the onpiation eater of anu. Theta ofa reer Nhe
er nl, 3 fcr 1 2 3% oF 6 Hee Row ale De compu by we 8 ene
Type ten)
lee mr xl ofc, a ec et aay
This progam gneraes the flowing capa:
fe
10
fiIntroducing final
A field can he declared as final. Doing so prevents its contents from being modified, making
it, essentially, a constant. This means that you must initialize a final field when it is declared.
‘You can do this in one of two ways First, you can give ita value when itis declared. Second,
Cer eee eed]
[Type text] Page 3:
you can assign it value within 3 constructor. The first approach Is probably the most
common. Here is an example:
cae
Subsequent parts of your program can now use FILE_OPEN, etc, 35 if they were constants,
without fear that a value has been changed. It is a common coding convention to choose all
uppercase identifiers for final fields, as this example shows.
{n addition to fields, both method parameters and local variables can be declared final.
Deciaring a parameter final prevents it from being changed within the method. Declaring a
local variable final prevents it from being assigned a value mara than once.
‘The keyword final can also be gpplied to methods, but its meaning is substan!
different than when it is applied to variables, This additional usage of final is po | penile
inthe next cnapter, when tnneritance is described.