Download as pdf or txt
Download as pdf or txt
You are on page 1of 25

6.

1 INTRODUCTION

As discussed in the previous chapters that aJava programis not p0Ssible without a classande cia
encapsulates data members (or variables) and methods (or function). The data member or variable contan
anyvalue like 4, 78, 3.4, B, 'n, "Liril", "madam', "BOOK', etc.
As far as method or function is concerned, in day to day life we heard about funetions, likeBirthday
function, Marmrage funetion, School's annual function, Sport's day function, ete., and you know ver
that each ot the tunction consist
of series ofevents. So, instead of telling each and every event o1 te
ceremony,we simply call it a function. In programming language function is also known as method a
method or function in Java programming contains series of programming statements and commans
pertorm a task or to nnd the solution of a problem. The Java language comprise of many built-in methogs
which can not be changes. However, it allows you to createyour ownfunction byusing any name
5.2 CLASSES IN JAVA
As discussed in the previous chapters that the underlyvingstructure of all Java programs 1 clasc
Anything you wisn represent in a Java program must be encapsulated in class.
to a
Clas8 defines the
classes. These objects use
state and behaviour of objects. The objects can created with the help ot
be
methods to communicate between them.
a new data type, such as int,
The most important thing to understand about a class is that it defines
float etc. Once defined, this class can be used to create objects of this type. Thus, a class is
a
blueprint (or
template) or an object, an object is an instance of a clas_.
and You will often see the two words object and
used interchangeably n this bok.
instance
5.2.1 The general form (or Syntax) of a Class form (or of class definition
A class is declared with the help of class keyword, The general syntax) a

1Sshown below-

class name-of-class
mportant: The terms used within square
(static) data type member-variablel; brackets 'are optiona
static) data_type member-variable2;

static) data_type member-variable-N;

lparameter-list or list of variables])


return-type or
data type method _namel

of method or statements
I/The body
W/end of method1
method_name2 Lparameter-list or list of variables])
return-type or data type
Important: The return-type or data type may be
IThe body of method or statements void, int, char, foatlete. The data type void is
W/end of method2 non-return type and restare
return types. Te
Concept of return is diseussed later in this chapter

lparameter-list or list of variables] )


return-type or datatype method nameN
Important: The method namel.N means name of
IThe body of method or statements function or variable. In the previous chapters the
program-contais method or function names as
W/end of the method-N
Demo ), showO, Display ), Compute0 etc.
the class
Classes and Methods (or Functions) 95
In the above general form, square brackets are not the part of the class definition. Actually,
inside the square brackets is optional. This means that the following code defines a valid class definit
Example
eass MyClass

In the above general form, the first line is commonly known as class declaration; and braces of
Class forms class body. Class body contains the declarations for all its variabies and methods. of the
The variables defined in the class are normally known as memberariables (or instance variable
To perform certain task another compound body is defined within the class, simply known as mem
methods (or methods or functions). Collectively, these elements, member variables and methods
are
kinown Consider the following code
members of theclass.
-

as

Example
class Table

double length;
double breadth, height;

In the above example, a class has been defined with the name Table, containing three instance
variables: length, breadth, and height along with data type:
double.
Currently, the class Table contains only variables but no method (or function). According to the
symtax, It 1s okay. But, to run a program successfully one or more methods must be defined within the
class. Refer to chapter 4 to understand how to create/declare object of class. This has already been discussed
in the previous chapters.

Also note that when a class is declared, no memory is allocated to i variables. This i
because a class is only a blueprint.(Memory spaceis allocated.-when objects of a class type are.create
instance
(Refer terehapter 4).
SZ2 Instance Variables, Class Variables and Local Variables
As discussed in previous chapters that every class contains its members ie. member variables and
methods The member variables are used within the methods) to do some task, A classcan contanany/all
of the following variable types supported by Java:
.
Instance
classis Variables:instance
known as Avariable
an
that is created
separately
variable. For example,
for
everyinstance (or object)
class has if a
of the
then there would be three
three instances
(or objects,
copies of instance variables, one for each instance (or object).
In other words, instance variables
belong to an instance (or object) of a class. Another way
o
saying that is instance variables belong to an object, since an object is an instance of a class
Every instance (or object) has it's own coPy of the instance variables.
2. Class (or Static) Variables The data member instance variable which is declared on
or

once-ter a class and all instances (or objects) of the class-wit strare this single copy of the class 1
known as
static or class variable. The 'static' keyword is used to declare a static or class vania
3. Local Variables: The variables declared inside methods
(or compound blocks) are called local variables.
(or functions),
constructors or bioc
The variable will be declared and initiazedwithin the
method and the variable will be
when the method has completed i.e.
destroy
the local variable _cannot be used or executed outside
SCope SCope means the area within the curly braces '

')
Classes and Methods (or Functions
To understand the diiterence between instance
and static variables, consider the
Example
following coae
class Samplel

int a instance variable


float
static int count,
instance variable
class variable, because the variable has keyword "static
Suppose, there are three objects created for the class Samplel. Then, there would be three copies
and
f instance variadies
higure D.l
Dut, there would be only one copy of class variable count, as shown in ne

int count space for static


orclass variable count'
Class or static variables
cOunt for all the
instance (or object)

int aemory space intaemory space Memory space


int
n
J O r Darlaote a J o r varable a '
for le a

Memory spu
float f Memory space float f Memory s loat
oat for variable T
for variable 1 JJor variable f
Instance variables Instance variables Instance variables
a and f tor second a and T for third
and f for first
a instance (or object) instance (or object)
instance (or object)

Fig. 5.1: Class variables and istance variables

static
with static keyword (for eg.
Note that the word static is a keyword. The variable that begins
becomes a class or static variable.
int count; etc.)
The variables defined within a class
Non-static
are
instance variables because each instance
called
of these variables.
(i.e., objec) ol the class contains its oWn copy body do not
variables are not shown, because the class
Note that in the above example the local 3
and 4, many (almost al) programs/classes comeams
contain any method (or function). In previous chapters variables.
all the variables are local
and inside the meti.d
a metiod tOr function) Variables and Local Variables
5.2.3 Difference between Class Variables, Instance
class variables is; The class o r
As discussed in point the difference
5.2.2, that between instance and of a clas5s
all the different instances(or objects)
copy that
18 shared by
SLatic variables only have one
instance variables a c r o s s

personal copy of an nstance variabl S0,


Wnereas every object
has it's own can have
varnables across different objects only
whereas class
aferent objects can have di/erent values compound block
wil be declared and initialized within the method ormany s that the loca
onevalue. The local variable when the method has completed its task,
it e a n

and the variabte wi be destroyed

variable cannot-be-aeeeseed-or executed o


used outside its SCope
FUNCTION(S))
.3 METHOD(S) (or use. We should add methods to
methods)i nhas
no
(and without
Practically, a class with only data or stance
variables) contained in the class.
for manipulating the data
(class or
static variables or suubroutine8.
e Class functions, procedures,
subprograms
1ethods are also known as

97
Classes and Methods (or Functions)
In the chapters 2, 3 and 4, you have been
using methods (or function) to write a progra
problem, 7his chapter will make you understand various features and applications of meth
hods.
Methoda (or functions) ofa class are declared inside the class body. A class can contain
ofmethods (or functiona as there t no such limitr any
To run or execute the statementa given within the method (or function), the method shoula
or
invoked or executed. A method (or function) may be called or invoked or executed any
numbere
inition A self-contained program structure that contains one or more statements to
specific task is known as a method (or function) OR a Java method is a collection of statement
grouped together to perform an operation or task. tha
A method or function has the following built-in features:
)Method (or function) prototype or Method (or function) declaration
D Method (or funetion) definition
Ti Method (or function) calling or invoking or executing the statements withi
method body
The general form (or syntax) of defining method (or function) is
Optional
Compulsory Compulsory Optional

modifier ] return_type or data type name of_method lparameter list or Signata

iThe body of method which contains programming statements to perform some


task
The finst line of method definition is known as
the
method (or functionl prototvpe ldeela
followed by method body. The method body is
composed of the statements to be executed delimie
by curly braces T ) . The method prototype or declarator
parts:
of the method has the following
Rermember that the terms given within the
square brackets T
The term modifier may be public,
are
optiona
private, protected or default. The use of modifier is option
1.e. you may omit). If modifier is not used (or omitted) then it
automatically becomes default.
is used as
public static or private static or protected static. The term static is also option
One purpose of static you have seen in variable declaration, the other 1s purpose discussed laie
The return_type compulsory part
or
data type is of the method (or function). It may
short, int, long, float, double, char, byte, boolean, String, void or class_name (mee
reference type)lhefunction returns a value as per the type meptioned. If void is used then t
method never returns any value (this 18 known as returning empty set of vaiues Tnus the vu
data type 1s also known as non-return data type).
A keyword return is used for returning
a value. U'he return statement causes the control 0
to the method (or function) call
statemen It means the method returns its value at
that p
where the function is called or invoked. it is like that suppose one of your friend needs a D
from you, Iriend will call you then you will return that book at that
so when your place w
your friend has called).
Also, remember that a method (or function) returns
only and only one value.
The name
of method (metlhodname) is also
body, It may be any defined name other than a
user
compulsory. It is an identification of
the de t
keyword. Rules for naming a method I
as for identifier. Parentheses a r e necessary after the method name. It
may be empy
An optional list of parameters or signatures, on which the method enclas
will operate, must be ea
within the parentheses (). This list contains the variable names and their eparate

data tYpes is
l i s t 14
by commas (also known as method signatures). The syntax of of defining parameter
98
F u n c t i o n

Classes and Methods (or


datatype variablenamel I, datatype variablename2,.
Let us consider the tollowing example of method (or function) definition:

Examplel1
Return-type Name of Method List of parameters
or data-type Or function or variables
Modifier
method protoPe
public static void
display (int w, char h, double d) This is

od ystem.out.pnntint w+h + d); /this statement will run when the function 1s invoRE
ition
body
In the above example the details of various terms are as

, public static - T h i s 18 modifier or access specifier


v o i d - h i s 18 return-type or data-type (void means that the method will not return anyuinE

I display This is name of the methodof(or funetion)


parameters or variables or
Method Signatures
int W, cunr 0D1e a This is list
Let us consider few more examples of the method (or function) definition:
modifier
without static modifier Example 3: Method without public
Example 2: Method and parameters
and parameters
static void displayO
public void display (
System.out.println( 3+ 4); System.out.println( 3+ 4);

modifier
Example 4: Method without modifier and Example 5: Method without static
and with parameter (int y)
parameters
public void display (int y)
void dinplay )
System.out.printin( y*4 );
System.out.println 3 +4);

7: without modifier and


Example 6: Method without modifier
public Example Method
and with parameters (int y)
with parameter (int y)
void display (int y)
Htatic void display ( int y)
System.out.println( y* 4 ;
System.out.println( y4 )

static modifier
Exmple 8: Method with modifier and
with Example 9:
Method without
parameters
and with return type and no
return-type and n o

parameters
public static int display () public int display ()
is int
return 3+4 ; I/function's data type
must. return 3+4 )} function's data type is 'int'
I/so return i8
/s0 return 1s must.

ldsses and Methods (or Funetions) 99


modifier Example 1l:
Method with modifier, with
Example 10: Method without static type and parameter (int y)
and with return type and no
display (int y)
public static int
parameters
int display (0 return y+4 } function's data type 8
int
IWso return 18 must.
return( 3+4)} function's data type is int
/s0 return is must.

without statie modifier, Example 13: Method without publie modit.


er,
Example 12: Method with return tyYpe and
with return type and parameter
parameter

public int display ( int y) static int display (int y)


return( y+4} /function's data type is int
)} function s data type is int
/so return is must. return y+4 /so return is must.

Example 15: Method without static modifier,


Example 14: Method without modifier, with
with return type and parameter
return type and parameter

int display (int y) public char display (int y)


(char) y ); /function's data type is
return y+4)}/function's data type is int return /'char so return 18 must. Here
Wso return is must.
l (char) is ype casting

In all the above examples different forms of method (or function) definitions are shown and the
return. The concept of return' is
int' and char' are shown with the keyword
return-typelater data-type
discussed
or
in this chapter. You may use any form for the method (or function) definition as required

In the chapters 3 and 4 various program are shown, where every class contains methods (or functions)
but without parameters. The following complete program makes you understand that how the parameters

are used and how they work?

Problem 1
Write a
program to create a class Box, with the data members width, height and depth (all in
w, h and d, to initialize them to the
decimals). Define a method void getData( ) along with parameters,
Calculate and print the volume the box.
data members of the class. of
Solution:
class Box

double width; l instance variable or data member of class


double height, depth; l instance variables or data members of class
public void getData double w, double h, double d) / Method or function 1, here variables
/w, h, d are parameters or arguments
width =
w; assign
height = h; /assign or copy h
or copy 'w toto height
width / or local variables or function signatures
depth d; / assign or copy 'd' to depth
double vi / here 'double
V width
v is a loeal variable because it is declared within the method
height * depth;
getDatal
/lcalculating the volume
System.out.printin(The volume =+V
/end of the function getData( )
W/end of the class

Classes and Methods (or Function


In the above class named Box, a method void getData() is defined. Its me

method oxs n
return type ales
ny value. It accepts three parameters of data type double in local varan
his
w. h and d e n nstance variable width, height and width. A new variable'v of douie
data type 15e e e 5 o r e t h e result of the ealeulated volume. The 'v' is a loeal variable as s
the method
declared-inside- getDatat ).
Follow these steps to use this elass in Blued:

1 As described in chapter 2 and 3, create the above class (ie., Box) in a BlueJ project and compileit.
Ater the c o p message"class compiled - No syntax error" appears, then close this
window to cone o n e project windoW, Here, an orange colour box containing the class n a n e

appears a5 snown n ngure B.2. Now, right-click on this elass name and click on the "new 5Ox *
new window as s 0 W n i g u r e 5.3, appears containing a n instance (or object) " b o x l C H c K

red colour box on the bottom left corner of the window as shown in figure 5.4, appears containins
instance o r o o j e c t n a m e b 9 X and class name "Box". Now, right-click on this object name, a n a c

on the method vold EetData( . . ) to execute i t (Referto figure 5.5).

hegect tde Tooh Viw Hep


Bluel Create Obyect

D aEO
BOx)

Name of Irnstance: box

Cance
Remove

Fig. 5.2: Complied class In this window, right click om icon FIg. S.5: T s winlow i s creattng instance
or oject boxi Jor the cluss "Box
then click "new Boxt)
Bot aPpears
"Box on

PrOYect tdt Toos View Help


roject Edit Tools View Help
New Class

box
void getData(doubie w, doubie h, doubie d)
bOxt

Inspec
baxiBoX
bort Bos Remove Fig. 5.4: The red colour area shows the name of
the metliod votd
Fig. 5.5: Select and click On Ceated stance or object "box for the clas "Box
getDataf..
2. After clicking on the method void getData(..), a dialog box "Method Call" will appear on the screen,
of parameters w, h and d. Type the values
as shown in the figure 5.6 which requires the actual values
then click "OK
of your choice a s shown in the figure 5.7,
Blue Method Can
Blue: Method Call Space for the Actual
actual values of values of
od getData(double w, double h, double
void getData(double w, double h, double d)
h. dd
Varnabies W, n, d rariables

. ,, d
boxi.getata ( oub box1.ge Data (12.5
ole h input by
1 Soube
the User,
dovble d 103 double d

click OKU

Cans o Cence
Fig. 5.6: Method call dialog bo requres Fig. 5.7: NMethond call dulog bos conlains actuul
ucTl values of w. h and d as nput input values of w=l2.5, n=5.0 and d=l03

Classes and Methods (or Functions) 101


After clicking "OK" on the figure 6.7, a new window Terminal window appears as shown i
tigure 5.8 containing the
tigal result ot the progra. tha

The volumo 6437.5

Fig. S.S: The "Terminal Window" comtatns the fnal result

Problem 2: See the problem no. 1 in different way as follows:


Write a program to create a class Box, with the data members width, height and depth (all
decimals). Define a method void getDatal ) with parameters, w, h and d, to initialize them to the da
members of the class. Define another method void volumel ) to calculate and print the volume of the
Solution:
b
class Box

double width; / instance variable or data member of class


double height, depth; / instance variables or data members of class
publie void getDatal double w, double h, double d ) / Method or funetion 1, here variables
Iw, h, d are
width= w, assign or copy 'w' to width l or local variables
parameters or
arguments
or tunction signatures
height= h; assign or copy 'h to height
depth d; /assign or copy 'd' to depth
H/end of function getData( )
void volume() I
Methodfunction 2 to find volume
or

a n d print the result


double v; s e e that double v' is a local variable because it is inside the method
volumel)
width *
V
height* depth;
System.out.println("The volume = "+V}
lcalculating volume

end of function volume(


//end of class
Note that, the above problem no. 2
volume(O in one class. As mentioned in the
contains two methods or functions void getData( ) and vold
concepts that a class may contain number
of methods.
Type this
program in BlueJ environment. After successful
(as in the problem
no. 1), then after
compilation create the object or instan
right click on the instance or object "box1", a menu will show
methods defined in the class as shown the t
method
in figure b.9. Select methods or
funcetions one by one. Pirst se
getData(.), then input the
again right click on the instance or
values ot the parameters and click "OK" (refer the figure 5.10), then
object and select the method
volume( ) as shown in the
Window appears containing the result as shown in the figure figure d.i
and click. Finally, a "Terminal

Bvek Method Call


5.12.
Select and Actua
click on the oMl values or
method getbata(double w, doubie,oo
getDatal
variables
W,
box1-oetData (12.5 & input D
wold gelData(doutde, doubie h, deudle S.0 double h the u
void vourme
d)
103 0oubled clickO
napec
as:Bol Remove
Fig. 5.9: This dialog box contains a menm
with hwo methods geiDatal..) and volumet Fig. 5.10: Method call
dialog box contains acta
npur valiues of w=l2.5, h=5.0 and d=l03
102
Classes and Methods (or Funct0
Temin Window-
Select and
click on the Optioes
method The volumo 6437.5

volumel
void getDala(deuitie. o u t i e h, doubie d

O me0
Fig 5.12: The Teminal Wanudonw
inapod t a t n r the finat result

Remove

From the m e i u elect anil ctick


Fig. 5.11:
on the method volumet)

CREATING OBJECT/ INSTANCE OF THE CLASS


5.4
In Java, is assumed
an objectonject to be a block of memory that contains space to store all ne
is done by using the new operao
Creaung an known
(also instantiating an object) as
variables.
Thenew operator Creates an object ot the specified clas8 and returns a reference to that opeet
a box then uhe
if assume class a as
o
open
a
lock, a key is required. Similarly, you
In
simple terms, to the clas8 (or box).
object of the class 18 t h e key
the objects or instances are created by right clicking on the DOX
In all the previous 5olved programs instance
own a s
n a m e of its
the and the Java compiler provides with an object or
containing claSs name . Let the class name is OFFICE
the figures 5.13, 5.14, 5.15 and 5
shown in

am
red
the Fig. 5.15: This winado shonws
10
e color D
Fig. 5.13 The windo Fig. 5.14: Right click on o
createo oject
nlees ne
or Lstance
contans class "OFFCE "OFFICE. in the menu new
oFFICET as object
LSTance o t I C E I
to be crealed.
OFFICE shows to create object
the statement.
describes the creation of object in physical form by writing
But, the following concept
15
The (or general torm) to create an ObJect
syntax
);
class_name objectname or variable = new class_name(

Here, elass_name : means the name of the class dehned by-the use
be any
objectname or variable : means the name of the-ebjet-oF-Instance to be created This may
o r any except variable keyword.
name, place, things
ne: is dynamic allocation operator that ereates the obiect and returns a reterence to that object.

class_namel ) :this part of theobiect creation is known


as
constructor function, it means the
ot object, if constructor function
constructor function runs at
the time ot creation
automatically
otherwise t h e J a v a compiler creates it.
present in the class
is

special method or funetion ofa class defined by the same n a m e of the clasSS as

onstructor: Awhich initializes the data members ot the class 18 known as a constructor.

Student is declared as
there is a class named
For example, suppose
class Student

int x; double m; char ch; data members or instance variables within the class

Classes and Methods (or Functions) I03


To ereate the ohject or instane of the above class, any one of the two methods can be uUsed
ed
Method 1: Objeet name or Dynamie memory Construetor method, See that
class name is Student and
nstance or Varialble allocator
Name of the elass funetion is ereated by the sam na
th
of the class; Student( ).
Student obj new Student);
As diseussed in earlier chapters that, an objector instance acts as factory of the class, so afer
execution of the above statement the object or instance obj' will contain the defaull inilial valuesof
of e
instance variables declared within the class as shown in the figure 5.17
=0
obj ch m= 0.0

Fig. 5.17: 1Defisult values of each instance variahles contained by the otject or mstance ob
Or, you can also write the above statement in two statements, like
this
Method 2
Student obj; / this line declares an object name or instance, like 'obj' here
o b = new Student( ); creates memory to the object 'obj' and runs constructor

The above two lines ofereating object or instance will behave in the memory as per the commer
entioned against each line. The status of the object or instance for the two lines will be as shown in t
figure 5.18:
After Line 1: Student obj; obj mull
= 0 m= 0.0
After Line 2: obj = new Student); obj ch=

Fg S.18: Declarutiom of object or instunce and initialization of euch instance variable with default values

5.5 CALLING OR INVOKING OR EXECUTING METHODS (or FUNCTIONS)


This
functions. Let
is veryimportant concept of programming
where the tasks are performed
using methodse
usunderstand this p r 8 8 in a simple concept, suppose a student has
requested to
his
/her friend
his/ her
about making notes for a subject. To get back or read those notes, the student has one d to cal
friend at a des1red place.
In this reference, making notes is similar to method or
friend to read the notes is similar to calling or
function definition
and calling the
get or
invoking or
So, only
executing the method (or function
defining/creating a method/function will not do, it must be called or invoked
also
execute
the statements given within the method/function body.
PEfinition : The process of executing the method (or function) definition body to run (or execute)a
the statements is known as
calling or
invoking or executing or accessing a method (or function).
A
method/function is called (or referenced or invoked) by specifying its name along with
t
parameters or arguments or
function signatures (11
parentheses ) wll be
given) within the parentheses-{) otherwise
empty. 1he method call 1s

Remember that while


terminated bya semicolon ().
calling or
invoking or accessing or executing a
must not be used. methrod/function the data 9
Executing the method call statement causes the method/function
transferred to the method/function definition, all the statements in the body to execute, i.e. contrl
and then control returns or comes back to the
method/function body are execu
statement following/next to themethod/function call.
Consider the following example class Student" to understand the concept of method calling

104 Classes and Methods (or Function


Example
class Student
void show int roll_no, double
total_marks)
System.out printin Koll number =" roll_no Total Marks =total_marks,

Now, to
Call or inwOKe or access or execute the method/function show ), the given statement 1s
3S21,
showt 4613 This is method/function call
statement. As mentioned earher,
at

Call a method only its name is used WITHOUT data type (void,
9 te but along WITH parameters, if given. See that the values
, 461.5 passes/goes to variables roll no and total marks
spectively and after executing the print statement given within
the method/function body, the output will
be as:
Roll number =3321 Total Marks = 461.5
The method/function show) can also be called or invoked or accessed or executed as:
int x= 3321; double m
=461.5; Ivariables are initialized with the required values
showi x, m *
This is method/funetion call statement. In this
case two
variables and
m are initialized with the required values and these variables are used
wthinthe parentheses "O', then values of variables * passes/goes to
rollno and 'm' passes/goes to total_marks. After executing the print
statement given within the method/funetion body, the output will be as:

Roll number =3321 Total Marks =461.5


Calling or Invoking or Accessing or Executing method/function with the help of the Object or
Instance ereated within the class:
Note that every method/function is called or invoked or accessed or executed with the help of its
objiet ar instance. The object or mstae may be created by the Java compiler itself (refer point 5.3 figures
5.13, 5.14, 5.15 and 5.16) or by writing the proper statement to create object or instance as mentioned in
point 5.3 (blue rectangular box).
Tocall or invoke or access or execute a method/function with the help of object/instance created within
theclass, the follouLng syntax or general form will be used
Object name . Method/Function_name ( list of parameters without data type, if any)
To call or invoke or access or execute data member/instance variables with the help of object instance
created within the class, the following syntax or general form will be used

instance_variable_name;
Object name data member .

Remember that the dot/period (.) is known as Member operator and used to call the members of
class (method/function or variable) apart from declaring a fractional value.
Let us consider the following example to understand above two concepts

Example
class Student
int num,
t h i s is data member or instance variable

void show int roll_no, double total_marks)

System.out.println'Value of num= + num+ krounumber= + rO1lno+Total Marks="+ total_marks);

Classes and Methods (or Functions) 105


Runt) Ithis is new funetion in which the object or instance is created
void
llcreation of object or instance of the class. Line .
Student obj = new Student( ne no
no.2
obj. num =125; llcalling num' and assign 125. Line
no.3
obj. ahow 3321, 461.5 ), lcalling method show( ). Line
V/end of the class
Now, see the status of the object obj' after the execution of Line no.1, Lune no. 2 and Line

when the method/function RunStudent


)is invoked or called:
obj = new Student obj n At the time of object o
After Line 1 cTeation
value 125
After Line 2 obj . num =125, obj = is assigned to nua
num=125 object 'ob) updae
with two itself
After Line 3: obj. show 3321, 461.5; obj olno=3521
totaln ks=461.5values, roll 00
no
total marks
when Line no. 3 runs, value 3321 copies to variable 'roll _no' and 461.5 copies to variable 'total mart
after that the following output will be printed because method/function show) contains a print stateme
Output: Value of num= 125 Roll number= 3321 Total Marks= 4615
The following program illustrates the creation of object(s) or instancets) within the class-

Problem 3 sslae
Write a program to specify a class Rectangle, with the data members length and breadth
decimals). Define a method void showArea ) to compute the area of rectangle and print it. Define
another method void RunMe() to create two objects and initialize each instance variable with differen
values and by calling or invoking the method showArea( ), print the area of rectangle for all the values
Solution:
class Rectangle ldeclaration of class
double length, breadth;,
void showArea()
cdata members or instance/global variables of class
llmethod or function definition to compute area

double are = length * breadth; *are is local variable to store the computed area
System.out.printin"Area of rectangle is = + are );
/end of the function showArea()
void RunMel ) aoil lnew method or function definition to make object or instance

Rectangle objl = new Reotanglel );


llcreating object or instance using methoa
objl.length =5.4; calling or
initializing variable length' with a value 5.4
objl.breadth = 2.0; Il calling or
initializing variable 'breadth' with a
value z0
objl.showAreal ); calling invoking function of class using object or inst
or

objl, now the function showArea(O runs using values


/ length=5.4 and breadth=2.0 that in
are 'objl' and prints
Rectangle obj2;
obj2new Rectangle( ); lereating object or instance using method2
obj2.length = 7; Il calling or initializing variable "length' with a new value 7
obj2.breadth = 4.5; calling or initializing variable "breadth' with new value 4.0
obj2.showAreal ); l calling or
invoking function of class using object instanor
objl, now the function showArea( ) runs using values lengu
and breadth=4.5 that are
in 'obj2' and prints resul
/end of the function RunMe()
llend of the class

106 Classes and Methods (or Functo


utput: The following is a
computer generated output:
Area of rectangle 18 = 108
18 31.5 t h e output on the values contained in the
object oD
ot rectangle oDJ
output on the values contained the object
Area e in
The above program18Just showing the two ways of creation of object/ instance and als0 caling
metnods refer topie 5.3 and 5.4).
invoking
ype the above program in Blue) environment. Compile and create the objectínstance provided o
Java compiler hen ng Cck on the object/instance and click on the methodfunction Runle, t
will create tw 0D natances objl and 'obj2. After that 'obj1' will be initialized with length0
breadth=2.0tnen uncton showAreal) is called or invoked, where all the statements inside the me
will run and rellects their result on the basis of values within object/instance objl'.

Similarly, oject ob will be initialized with length=7 and breadth-4.5, then again methodruneon
showAreal 15 called or invoked, where all the statements inside the method will run and retlects tner
result on the basis ot values within object/instance 'obj2.

5.6 TYPES OF METHODS (or FUNCTIONS) WITHIN THE CLASS


Similar to variables, the class may have two types of methods (or functions) as follows
1. Class Methods 2. Instance Methods
1. Class Methods: All the methods/functions defined using the keyword 'static' are known as staic
methods/functions or class methods/functions.
Example1: public statie void show()
statie void show) lyou may also write

System.out.println(T am static method );

Refer point 5.3 containing various examples. The static methods/functions are called or invoked
either through another static methods /functions or non-static methods/functionsor using the
class name followed by dot ( operalor and method/funcion name r the static method/frunction
is to be invoked/called from a new class)
static void show() you may also write public static void show()
Example 2
static method");
System.out.println( I am a

that of general utility but do not directly affect an instance of that class is usually
Methods are

declared as class methods.) Java class library also contain a large number of class methods. For
example, the Math class defines many static methods to perform mathematical operations. One
this b0oR) 18 Used as: Math.pow(3,4;
of its method named pow() (will be discussed later i n
Note that, before the dot operator we have used the class name (1.e., Math), then dot operator ()
and then its static method name (i.e., pow( )) with the required parameters.

2. Instance Methods: All the methods defined WITHOUT the static keyword are known as instance
methods/fiunctions or object methods/functions or non-static methods/functions

void show) you may also write public void show()


Example:
System.out.printin("T am a non-static or instance or object method");

Refer point 5.5 containing various examples. They are called or invoked or executed either through
the object (or instance) of the class (refer example under point 5.5 and problem 3) or by just using
the methodiijunction name
For exampte, all of the methods in earlier solved programs (such as: getData( ), show( ),
showArea( ) and volume) etc.) are nistance methods or object methods or non-static methods.

laeses and Methods (or Function


107
METHODS
INVOKING) STATIC and INSTANCE
5.7 CALLING (or
and instance
methods/tunction with the help
Let us understand calling/invoking static s
example:
1. Calling/ Invoking / Executing /
Accessing Class lor Static)Methods
called or invoked either through another static met m

methods/funetions a r e dot (J opero


class/static class name followeda 0y
The or non-static
methods/functions or using the
invoked/called from a ne1ew
functions is to be
methodifunction name tif the
static method/function
tai
See the following examples:
Example2
Examplel calling
or invoki ng
c a l l i n g o r invoking
Istatic show ()
method

through method demo ()


statie nothod ahew
through other atatic class Sample2
method demo ()
class Samplel static void show
s t a t i c void show() system.out.println ("static") ;

System.out.println("staticC) Static method Static method


void demo ( ) //non-static show) is calld
show) is
called through
through noO
static void demo show( ) static method
static method
demo)
show( ) , demol) //end Of classS

1//end of class
Class compiled- no syntax errors

Class compiled- no syntax e r o n

Example4:
Example3:
calling o r invokin9
aangoE invoking
1 thod ahow static method show()
Static method
through another class
h anathe class show) is
ietatit tanction deno Static method class Sample4
called through
class Sample3 show) is called
s t a t i c void show()
through static non-staticC
s t a t i c void show() method demo
method demo(. System.out.println("static")

i n a new clas
ytes.Out-pranEIn°staEzC ) in a new class
1 e n d ot c l a s s Sample3
run'
/fend of class Sanple3
run' as:
making another class below Sample.spo
/making another clasa beiow Samples.show. ublic class Run
Sample4 ells
public class run Sample3 tells that method
that method
5tae void demo()/non-sta show 15
ata tic void demO
show) 18 member
member of class
Sample3. show( ) <
Sample4.show) class Sample
| / / e n d off naw class F
Samples. rend Or new class Ran

Class compiled-no syntax errors Class compiled - no syntax e o s

2. Calling/ Invoking/ Executing/ Accessing Instance or Non-Static Metho


fhe instance/non-Static methods/functions are called or invoked either by using the object/instä
method/function
of that class where the method/function belong to or directly by using the nor"

As shown above in classes "Sample2" and "Sample4" the method/function void demo15 1ar)
static or instance method/function and is calling or invoking static method show(O. S
the non-static or instance methods are invoked.

Consider the following examples: e t i o n

Classes and Methods (or Fune


108
Examplel
Example2:
calling o r invokirig
/ calling or invoking This
/ / non-static/instance Btatement
show () with the
7/method show () through help of object or Createn
object or
11/ non-static or instance Lnstanco in mathod demo
method demo () class Sample6 instance
'ob' o
class Sample5

vOLd ahow( 1instance ethoa class


void ahow 9 /instance mothod Sample6
yate.out-pEAntin (Non-tatACT)
system.out.pEAntln ("Non-atatic"); tance This
method showovoid demo)inatance mathoa statement
calls the
void demo (/instance nathod 8 called /tollowing statement makes c instance
through Sanple6 ob nev sample4G() method
show()/calling instance method caling
inatance method
method demo) / t h t o u g h O0Ject G
using the
//end of class obiect or
a n d ot C a s
tance

Class compled - no syntax errors


Class compled- nosynak on

3. Calling/ nvoking / Accessing Class and Instance Methods using maint


The class and instance methods/functions can be called or invoked using standard Java bases
main() method/function. The advantage of using standard main( ) method 18that e
compiler arectly points to main) and start executing program or callingnvoking metnods
functions as per the programming statements. to be
The Java compiler treats main( ) method as the actual compound statements)
area (or
demo
executed. You may create many methods/functions (hke getbata), displayO, show),
) etc.), but, in order to run standard or stand-alone program independently everywhere, the program

must be created using m a i n m e t h o d .

The syntax or general form of the main( method is as:

public statie void main( String argsl y o u may also write Stringl) args

Statements....

access so the entire line


Note that, the main() method/ function begans-with public specifier,
becomes public (i.e. it can be accessed or executed externaly). The other methods/funcufons of the class are
called or invoked or accessed or executed from main) and also the object or instance is created within the
main ). Other details of the syntax are as follows:
It is access specifier which allows the execution of method/function from
public anywhere, It is als0 known as vIs1Dinty which means the method/function
main( ) is visible/available as public. It also denotes that any other class can
call the main) without any restriction.
I t allows the execution of method function without creating an object
static
I t is data type that means the main) method does not return any value.
void
It is itself the name of method/function. It's name will never change. The
main )
main() is special because it1s the start of the program.
String argsl1- It can also be used as String agrs lt is a parameter or an argument fo
main( ), where Stringl represents "array of string' and "args means
argument. In place ot args any other name can be used.

Classes and Methods (or Functions) 109


Consider the following example containing the main() metnod
Example 2:
Example 1:
calling or invoking
cal c/instance
/ calling or invoking non show () from
/Static method show() method )method

/ classtrom the main( )zothod Ehe ain (


Clans8Apiet
8anple7

Calling static void show()non-static method


atatic void ahow()//static mothod class method
show) from
system. out.printin
trnon-static
functio
System.out.println ("static function") he
method
main) /the main()
method starts below
public static void main( String argst 1
/the main( ) method starts below
publie static void main( String args[1
of the class
/creating object

show)7/calling static nethod Calling non Samples ab) new 3aple(

/ end of main( ) e thod Stauc metnouobj.show( ) caling non-static nethod


show) from using object obj
/end of class main( ) method
the main() //end of
/end of class
Class compled - no synax erors
method using
ODJece Class compiled -no ynk
You can easily differentiate between the two examples. In example 1, class Sample7 contains
staticclass method/function show() which is called or invoked from main ) method directly.and prints t
output "static function", whereas, in example 2, class Sample8 contains a non-staticinstance metho

function show) which i8 called or invoked from main) method after creating the object (or instanc
and prints the output "non-static function".
As already discussed that the class/static method is invoked directly without any prefix because iti
a class method and can be executed throughout the class, whereas, instance/non-static method cannot h
it the object/instance of the class an
executed directly, though it is the member of class, 50 require
through object
t h e method is called. You may also call or invoke static method function using an instana
object.
Remember that when you right click on the compiled class, the drop down
menu will appear as shown in the figure. Now you have to click on void main
String args[ })" to execute the main() method. This type of menu will always
appear if a class contains standard main( ) method/function.
Open Edlo

Comple

5.8 ACTUAL PARAMETERS and FORMAL PARAMETERS (or ARGUMENTS


As discussed earlier that every class must contain one method/function to perform a task. The methou
function within the class may contain one or more parametersvargunments. at the time of defining a
calling (or invoking) the methodfunction you have observed this in many programs in the previ
chapters and this chapter also). Now, you must understand that these parameters are knowm by specu
names as Actual and Formal parameters / arguments.

efinition: The list of variables given at the time of method definition along with their data tp
and also at the time of calling or invoking method/function without data type are known as parameters
Example ehar es, int y are the
parameters
void demo char cs, int ý) is function
This is This line prototype
method or M and 287 are the parameters to
function be passed to char cs and int y
definition
d
body demo( M, 267 )- T ' h i s is method/function calling statement

110 Classes and Methods (or Functio


Formal Parameters: The list
of variables given at the time of
with eir data Ypes
nen Known are
as formal or local or
dummy parameters
method/funculo
(or
Example argune
c h a r cs, int y are FORMAL parameters
This is method
old demO char cs, int y) This line is function
nction
prototype
or
********

definition body
Actual Parameters: The list
of variables given at
without their data ypes are known as actual
the time of method/function calling (or invorg
Example 1:
parameters (or
arguments).
M and 267 are ACTUAL parameters
demo M, 267 ) oldh
Example 2:
int x =
26 char mn =
"M; variables mn and x are ACTOAL parameters
demo mn, x }

Note that the formal parameters must be variables along with data type of
commas but the dctual parameters may be in the actual values (refer example 1) each
or
variable separatea
in the form of vdrio
bhich must contain some values (refer example 2, here variable x is assigned 267 and mn is assigned
To better understand the concept of actual and formal parameters, consider the following program
Program 4:

Wrte a programto create a class Rectangle, with the data members length and breadth (all in
decimals)., Define a method void Accept(O along with parameters, I and b in decimals), to initialize them
to the data members of the class. Another method void showArea( ), computes and prints the area of
) function to ereate the object/instance of class type and call the functions
rectangle,
Alsodefine a main
to print the area of rectangle.

Solution:
class Rectangle

double length, breadth; /data members or instance variables


the line below is where,l and b formal local
void Accept
method definition
double 1, double b)
are or
parameters
-1 and b are formal parameters
length
breadth
Massign formal parameter 1' toto instance
b; //assign formal parameter B
variable length'
instance variable breadth
1/end of method Accept()
void showArea()

double Wif you write double area=lb, then it is wrong because


area =
length breadth;
V and "b are local or formal parameters and cannot go
lout of its method scope
;
System.out.println(The area of rectangle =+area
/end of method showArea )
String argsl I) /this starting of main( ) function definition
public static void main(
Rectangle obj new Rectangle(): aking or ereating object 'obj' of the class
obj. Accept 23.0, 5.5; calling function that passes 23.0 to T and 5.5 to b'

obj.showArea( ) t h e s e are actual parameters


end of main( ) function fhne n
Vend of the class

lasges and Methods (or Function 111


the control returns
In the ab0ve pe, you have observed that with every method/function callin8 B t,the
able (like: 1nt y,
tioat cnar ms, double and boolean p) is present to receive m value ot the
data type as returned by the method/function. It is mandatory.
mandat cevethethe etum
However, n type function
sarme da
unction. It is
e c a e a or nvoked directly
as
as
) System.0ut.printin( The result = "+ sum(O I see that the function sum) 15 roked
here the return
vaut
withbeprint statement,
so

received by the print statement and w i u


will
/ be printed
( i i ) i n t m = x * s u m ( ) ;

See that the function sum(O is invoked with the calculation


statement, so here the return value will be tece ived tnen"
/will be multiply by * and final result is stored in mfinction
Consider the following example that clearly indicates that how the control is transferred from
statement to the function (prototype) and how the return statement behaves
all
Example
line below is function definition, here int means return type
int Sum( int m, int n) bere
int s = m+n,

return t s

Ifunction
void callMel)

here int R sum( 3, 5 ); fromthis place this is function call statement


System.out.pintin("The sum = "+ R);

In the above example, the arrows indicates the place, where the control is transferring it self.
Remember that the function call statement works in two parts;
at the nst
par", sum(3, 5) activates and
line), then the
the control reaches to first line of method I function definition (means method prototype
to and to n , atter that the control enters into
parameters passed (1.e. value 3 passes/copies
are m '5
executes all the statements (as int s=m+n) and when the control reaches to
methodIfunction body and
return (s); the second part of the method/function call statement gets activated and the return value of
in the method/function calIMel ), which will be printed after that. Note
Swill be received by variable "R' Also
n are tormal parameters.
and
that, here values 3 and 5 are actual parameters whereas m
at the method/function call statement must
remember that the return _data_lype and receiving_data type
be same, otherwise it will give an erTOr

more thing in method/function which will be discussed in


Note that, there are many
CLASSX as per the syllabus preseribed by the examination board/council.

Problem 5:
class Sample, with h e fractionat data members/instance variables A, B
Wnte a
program to create a

and C.
Define a method void Coordinates() along with parameters, X, y and z, to initialize them to the

ata members/instance variables ot tne


class.
Define another method double computel) to calculate and return the area of triangle using the

ormula: X = B. 4AC
create the objectinstance of class type and call the functions
Also definé a main( ) function to to
PInt the result of the relation.

lasses and Methods for Functions 113


Solution:
class Sample
instance variables
double A, B, C; W data members or

void COordinates( double x, double y, double z) method detinition


parameters
where,
where, a,y
y
and z
/ formal or local
variable 'A'
parameter * to instance
A= *, formal
SSign formal variable B
B y; parameter to instance
y'
assign to instance variable C
C z; parameter z'
assign formal
//end of the method function
Coordinates()
definition data type is double, so return is must
double computel
be usedin
in other metho
other
is local s o c a n n o t
/ variable * n
double X= B B-4 A C;
write return (A ;
return X; you may also
1//end of the method computel )
function definition
void main)
static t h i s starting of main( )
public
II Making or creating object BR of the clas
Sample BR =new Samplel
double m = 7, n = 5, p = 3;
;
initializing variables with some values
l calling function that passes value in "m' to * , r to
BR. Coordinates( m, n, p and 'p' to z i.e. passing actual parameters 'm, 'n', p' to
'"7
formal parameters 'x, 'y,
Ilcalling function to pertorm calculation and to recei,
double ans = BR . compute );
* to variable *ans here
/ receive the return value of variable

System.out.println(The parameter values


are + m +" +n+"+p)
"
"

llprinting resul
System.out.printnResult of X
=" + ans ;
W/end of the main( ) function
Mlend of the class
function main() is called:
Output: The following is a computer generated output when
Buet femnawOkea
Optons
values are 7.0 5.0 3.0
he parame ter
Result of X -59.0
=

Problem6:
data member/instance variable radins
Write a program to create a class Circle, with the fractional
to store the value of radius and. Detine a method void accept( double r) to initialize argument T
instance variable 'radius. Another method double computeArea() to calculate and return the area
circle using the formula: Area = T**
Also define a method void ShowOutput) to invoke the functions accept() and computeArea
to print the area of circle.

Solution:
class Circle

double radius; ldata member or instance variable


void accept double r ) function definition where, r is formal or local paramets

radius = Ilassign formal parameter P to instance variable radius


/end of the method accept()
n c t i o

14
Classes and Methods (or Func
13
double, so return
double computeArea(0 unction definition data type is
local
double area = 3.141 radius radius; Il variable 'area' is
(
return aea, you may also write return area

/end of the method eomputeArea( ) definition other than main(.


public void ShowOutput()
Wfunction
circle
variables as
redius of
double red = 12.5; initializing
value in 'red' to T i.e. passing actun
accept( red C a n g function that passes
T
to formal parameters
parameters "red' calculate the and toto
area area'
double area_circle = computeAreal ); lcalling function to
receive the return value of variable
ShowOutput()
'area_circle' in
the variable
resuits
+red now printing
System.outprintint value ot radius
System.out.printin("Area of circle="+area_circle
function
Wlend of the ShowOutput()
class
the
Wlend of ShowOutput()
15 c a l e d :
method
generated result when
Output: 'The following
is
a computer
Bluek Teminal Window- d
pbons
12.5
value of radius
=

Area of circle 490.78125000000006

main( ) method
that in the program 5,
a

ditferentiate between the problem 5 and 6, are


called/invoked
You may easily created inside it,
then the
methods/functions
are
s
of the class the
methods/tunctions

is defined and the object 18 defined


and
showOutput()
method/tunction
6 a
whereas in the problem problem.
You may use any
method to find the
solution
of a

calledinvoked.
below:
Consider one more example programs described

Problem 7: int m, int


n ) to return the sum of
method/function int display(
define a
Write a program to
m and n.
quares ot the parameters

Solution: without the u s e of any other


method/function
from the
returns value
program that
tunetion/method

class Example
parameters m andn
definition with formal/local
int display( int m, int n) I/ function
of squares of m and n
sum
Ifinding
n t sum = m m +nn,
Ilreturning sum
return sum,
Vlend of method display()
1/end of class
described below:
to e x e c u t e
the program is
by step process
Output: The step
115
lasses and Methods (or Function3)
Step 3 See the red b0x at the
Step 1 Right cliek Click OK on this window
2
Step
on class to make to make object/instance of cla8s bottom 1elt corner that
contains object "example"
object'instance. examplel" provided by compiler.

Bel: Create Object


New Clats
hew Eumple0
Example0
Cpen E o

Lompie Name of Inatarnce


mee1
Remove O Canc Lsamte

Step 6: Alter pressing OK, the Step 5: Now, the given windoW p * ugnt Chick on the
see Lhat ODect ana Belect method
value
(80) appears in the requires parameter values,
return 8, 4 for m and n, then click oA.
int displayl int m, int n).
following window. Clhck on
"close
the job is terminated.
B c Method Resut X Blue Method Call
New Class
nt dplynt a,ntn) nt displaytint m, tnt n)

eapeLdpiay3,
retmed: Get sanple1.6eplaY ( ntm
Commp
ntn

Kample1 nt dsplayint m,
Exanpe
ino)
Cose
Cance Inapect
eramble1Ex Remove

Problem8:
Write a program to define a method/function double Interest( double p_amt, double rate, int

time )-to return the simple interest using the formula: SI =


100
Solution:
program that returns simple interest from the method/function

class simplelnterest

double Interestl double p_amt, double rate, int time ) I function definition

double SI = (p_amt * rate " time ) / 100; I/finding simple interest using formula

return ireturning simple interest


/end of method Interest()
/end of class
Output : Use the same proces as in program 15.7 as: create object and call method the
input parameter values and click OK to get the "Method Result" window for the final return
value as the output:
Blue: Method Call
Blue: Method Result
@XThis is
These are doutie lnterestdoubile p_ami, double rale, int time) double Interest(double p_amt, double rate, nt tme) the fina
the return

parameter
values input
leln LInterest150000 daublept ATpleini.interest(1s000.0, 6.25, 5) pet value as
6.25 double rate rebrned: Get
output
by the user nt t e double
%687.5

Cance Cose

116
Classes and Methods (or Function
10 METHOD OVERLOADING (or POLYMORPHISM)
6.10
In simple understanding, the thing/object which is available in many
nle, the object "table" is available in torms i Table. Computer
Table, Dining Table,
Computer
many snapes u8, Study
forms as: 12 incneated by their
LED TV, Internet T
ODJect TV is also differentiated their
TV,
V, LCD all tables urseTV's but they
are or are

sizes and
other specífications. similarly
similarly,
Overloading refers to the use of the same thing/object for different purposes thodlfunction call
appears to pertform diferent activities depending on the kind of data sent to it in the methouu
tatement. 1his 1s ais0 Known as polymorphism in 00P.

Definition: The process of defining two or more methods/functions with the sane ut with
parameters (or arguments) is known method or function overloaaing
different akL DpEs o as

The advantage ot using method/ function overloading is that the program whicn co
concept Other programs because in case of method/function overloaang m
compiler loads all the functions and when they are called or invoked then the compile lem
the basis o paraneters (or arguments) or data types. The method (or function) overloading_ pleea
polyniorph1sm.

The need (or use) of function overloading:


1. Eliminating the use of different method names for the same operation.
2. Helps to understand easily.
3. Easy maintainability of code.
method/runcion
prototypes to understand the
Consider he 1ollowing examples of method/function
overloadingg
Examples (valid):
see, here the method name is 'sum(O and data type is void'
G) void sum()
here the method name is 'sum( and data type 1s "nt
(i) int sum I see,
int x ) see, here the method name is 'sum) and data type is 'void' and
(Gii) void sum x'
parameter is int is 'void' and
and data type
(iv) void sum( int x, char y) see, here the
two
method name is 'sum
parameter 1s int x and char y
In all the
Above few examples are shown to understand the concept of method/function overloading.
but their
data types are changed
eitherparameters/arguments.
(such as: void.
examples the name of method/function 18
sum
18 defined witn or wuhout
method/function
etc.) or
and int their data types (void and int) but in
The Java compiler differentiates examples
()
and (i) by
are differentiated by their parameters/
they
examples (i), (iii) and (iv) the
data types are
same (void) s0
arguments. So, it is a valid method/function overloading.
as follows:
Consider some invalid examples

Examples (invalid): and data is void'


the method name is
"sum type
() void sum Il see, here is also void'
the method name is 'sum and data type
(ii) void sum) Il see, here is int' and
l see, here the method name 1s ' s u m ( ) and data type
(ii) int sum( int x)
p a r a m e t e r 1s ' i n t x

name is 'sum( and data type is int' and


(iv) int sum( int Il see, here the method
m parameter is int m'
is is (which
tne method/tunction name same
a
All above examples are invalid because n and
that is why invalid'. In
valid case because overloading needs this) but type in both are 'void,
data

types and parameter/argument


xamples (ii) and (iv) again the method/uncaon nane 18 vula Dut tne data
here either data type or tany
paramete5
onej
shottt be changed.
ame,
FLsses and Methods (or Functions)
117
n o t confuse with 'int x' and int m, of course the variables '* and m are different, but it uit
h use as per the rules the data type (either before the method/function name or param
should be different. So, be
very careful while applying method/function overioaing
Consider the
following example program to understand the concept of method/function overload
Problem 9: ing
t e a prgram to create a class OverloadSample and overload method check() as followg
)
void check( char ch) to print next three characters including the parameter w
(i.e. 4 characters). It is assumed that the value of
parameter ch' is between 'a- w (lowercase). aracte
(1) void check( char chl, char ch2) to print the just previous character irom the
parameter 'eht
and 2nd previous character from ch2. Assumed
that
of character 'ch1' and 'ch2 are between C Z only. valu
the
iii)
char check( int m): the equivalent
to return
character 10rm ot argument
Assumed that the value 'm' 1s between 6b 90
or 97 -122
-

48-i67.
Also define a method void RunMe() to the above overloaded methods/runctions
relevant
invoke by passing
parameters/argument and print the results.

Solution
the following program the method/function
uses overloading concept
class OverloadSample
Inote, that there is NO data members in this class
void check( 1st overloaded function
char ch) definítion, ch is formallocal parameter
System.out.print The four characters are ");
System.out.println(ch+" "+(char) ch+1) +" "+ (charX ch+2)+" "+(charX ch+3) ;
W/end of lst method check()
void check( char chl, char ch2) I/2nd overloaded method
definition, chl and ch2 are
formallocal parameter
System.out.println(The previous character of + chl +" is= "+ (-ch1) );
System.out.println( The 2nd previous character of+ch2 + is = "+ (char)( ch2- 2)
Wlend of 2nd method check()
char check(int m)/3rd overloaded function definition, m is formallocal parameter
char st= (char) m; Il convert 'm' into character
form using type casting (Cchar)
return st;
l/returning
the
V/end of 3rd method check)
new character
stored in 'st' after converting m'

public void RunMe() l function definition other than


main( )
char sl= g; int y =
107; /
initializing character and integer
check( sl Il calling 1st overloaded function that variables
passes value in 'sl1' to on
check T, F ; lcalling 2nd overloaded
function that passes T' to 'oh1' and T
char st= check ( y }
Wcalling 8rd to "cn
Ivalue from overloaded funotion that
function will be recelved passes 'y' to m' and the reru
in character variable
I now printing results
System.out.printinThe character form of+y+ is ="+8t );
W/end of the RunMelO funetion
Wlend of the class

118
Classea and Methoda (or Funetion
Output: The rouowing 18 a computer Kenerated result when method RunMel ) 1s caledi

ptmn
The
rour characters are 1g 3

Th pEevkous
ou character of T
chaEACter of
i-

ot
CEer tom 107
i k

In the above prog, nside the method/function RunMe ), three overloaded methoas r
single paraeter, check("T", F)-with tn and check( y )-with single parameter
with t n two parameters
automatically distinguished that which
a compiler
be called/invoked
method is to be thus, ll
called/invoked and thus all the overloaded method/functions successtully execueu
method
Problem 10
Write a program to create a class number and overload method minimum) as follows:
arguments nl
(int minimum(
int nl, int n2):
to return the smallest integer from the
and nz, using the conditionavternary operaor
2
Gi) int minimum( int xl, int x2, int x3): to
the smallest
return using integerfrom the argumenhod
the suitable mathematical
method
and x3,
function.
Also define a method void PrintOut( ) to invoke the above overloaded methods/functions by passing
and print the results.
relevant parameters/argument

Solution:
the following program uses the method/function overloading concept
class number class
Inote, that there is NO data members in this
int minimum( int nl, int n2) I/lst overloaded function definition

intsmall= (nl < n2 )? n l : n2; /indig smallest from nl, n2 using ternary operator
lhreturning smallest number stored in variable 'small
return small;
/end of lst method minimum()
overlonded function definition
int minimum( int xl, int x2, int x3)

'sm
x2 ); /deciding smallest from xl and x2 and store in
int sm= Math.min( x1, deciding smallest from s m and
x3 and store in 'small'
int small = Math.min( sm, x3
variable small'
llreturning smallest number stored in
return small;
Wend of 2nd method minimum(.
l function definition to call overloaded functions
public void PrintOutl)

int m= 13, n = 24, p = 7


/ initlalizing integer variables
in 'm' to
int sml =
minimum m, n )} l
calling 1st overloaded unction that passes value
and
return values will
be received by "sml'
Il 'nl' and 'n to n2
i n t sm2 = minimum( n, P, m ll calling 2nd overloaded function that passes value in
'n' to *l, P to 'x?' and 'm' to x3' and return values
I will be received by 'sm2

now printing re8ults n+ is="+ 8m1 );


oystem.out.println( The smallest from+ m+ and
+n +P+ a n d + m +" is="+ am2 )
5ystem.out.println("The smallest from
function
/end of PrintOut(
Wend of the class

Gaes and Methods (or Functiona) 119

You might also like