7/30/2019 Topic 3 Part 1 Method
1/46
OBJECT ORIENTED
PROGRAMMING IN JAVAMethod in Java Program
7/30/2019 Topic 3 Part 1 Method
2/46
COURSE LEARNING OUTCOMES :
Upon completion of this course, the studentsshould be able to:
1. Describe the features and basic concepts of Javalanguage.
1. Write, compile Java source code and interpret Java bytecode using Java Development Kit (JDK).
1. Implement the key of OOP concepts: classes and objects,inheritance and polymorphism.
1. Incorporate exception handling in Java Programming.
7/30/2019 Topic 3 Part 1 Method
3/46
OBJECTIVES :
1. Create classes in Java program
1. Identify built-in classes in Java program
1. Create an object in Java program
1. Explain the concepts of accessing objects via referencevariables
2. Explain the concepts of accessing objects data andmethod
3. Explain the scope of variables in classes
7/30/2019 Topic 3 Part 1 Method
4/46
Preview Questions
State TRUE or FALSE1. A class can contain ONLY ONE method
2. The basic form of method must return astring
3. Worker methods can also caller methods4. Main method accepts an array of strings
5. A methods can only have one parameter
6. Methods cannot have the same name as the
class.7. Methods can be declares outisde a class as
a standalone method.
7/30/2019 Topic 3 Part 1 Method
5/46
Define Method
In a class is contained within one or moremethods.
The syntax of all method declarations is :
[modifiers] return_type method_identifier([arguments])
{
//method code block
}
7/30/2019 Topic 3 Part 1 Method
6/46
Where : [modifiers] represent several Java
technology keywords that modify the waymethods are used. Modifiers are OPTIONAL
return_type is the type of value return from amethod that can be used elsewhere in theprogram. Methods can return only ONE item(literal value, variable, object reference and soon). If nothing is be returned, the keyword voidmust be specified as the return type.
Method_identifier is the name of themethods
7/30/2019 Topic 3 Part 1 Method
7/46
The ([arguments]) represent a list of
variables whose values are passed to the methodfor use by the method. Arguments are OPTIONAL(indicated by the square brackets); many methoddo not accept arguments.
Themethod_code_block is a sequence of
statements that the method performs. A widevariety of tasks can take place in the code block orbody of a method.
7/30/2019 Topic 3 Part 1 Method
8/46
Basic Form of a Method
The basic form of a method accepts no arguments andreturns nothing.
The following display method from Shirt class is a basic
method :public void displayInformation() {
System.out.println(Shirt ID : + shirtID);
System.out.println(Shirt description : +
description);
System.out.println(Color Code: + colorCode);
System.out.println(Shirt Price: + price);
System.out.println(Quantity in stock: +
quantityInStock);
} // end of display method
This method prints several lines of information.
7/30/2019 Topic 3 Part 1 Method
9/46
Invoking a Method From a Different
Class To invoke/execute a method in a different class,
use the dot (.) operator with an object referencevariable to do to access the public variables ofan object.
E.g :public class ShirtTest {
public static void main(String args[]) {
Shirt myShirt;
myShirt = new Shirt();
myShirt.displayInformation();
}
}
7/30/2019 Topic 3 Part 1 Method
10/46
In this e.g, an object reference variable callmyShirt is declared and initialized to aShirt object (on line 3 and 4).
ThemyShirt object reference variable then
invokes the display method within theShirt object (line 6).
7/30/2019 Topic 3 Part 1 Method
11/46
Calling and Worker Methods
In the previous example, the ShirtTest classcall the display method from within anothermethod (main method).
Therefore, themain method is referred to as the
calling method because it is invoking or callinganother method to do some work.
Conversely, the display method is referred to as
the worker method because itdoes some work for
the main method. Many methods are both calling and worker
methods because they not only do some work, butcall other methods too.
7/30/2019 Topic 3 Part 1 Method
12/46
When a calling method calls a workermethod, the calling method stops executionuntil the worker method is done.
After the worker method has completed,program flow is said to return to the pointafter the method invocation in the callingmethod (return to line 6 in theShirtTest.java class)
7/30/2019 Topic 3 Part 1 Method
13/46
Invoking a Method in the Same Class
Calling a method in the same class is easy,justinclude the name of the worker methodand its arguments, if any.
7/30/2019 Topic 3 Part 1 Method
14/46
Guidelines for Invoking Methods
1. There is no limit to the number of method callsthat a calling method can make.
2. The calling method and the worker method canbe in the same class or in a different class.
3. The way to invoke the worker method isdifferent, depending on whether it is in the sameclass or a different class from the calling method.
4. You can invoke methods in any order. Methods do
not need to be completed in the order in whichthey are listed in the class where they aredeclared (the class containing the workermethods)
7/30/2019 Topic 3 Part 1 Method
15/46
Passing Arguments and Returning
Values Methods can be invoked by a calling method
with a list of arguments (variables or valuesto be used by the worker method).
Additionally, methods can return a value tothe calling method that can be used in thecalling method.
7/30/2019 Topic 3 Part 1 Method
16/46
123
910..
45678
Object 1 Object 2
V1
V2
Caller method Walker method
Value 1 beingpassed from
object 1 toobject 2
Object2returns value2 to object 1
7/30/2019 Topic 3 Part 1 Method
17/46
Declare Methods With Arguments
public void setFloor(int desiredFloor){
while (currentFloor!=desiredFloor){
if (currentFloor
7/30/2019 Topic 3 Part 1 Method
18/46
The main Method
Main method also accepts arguments, one or more (an array)
of references to String objects
public static void main(String args[])
Why must the main method accepts these arguments?
The Java programming language requires that the
main method be written so that it can accepts
values when you execute the program from the
command line.
7/30/2019 Topic 3 Part 1 Method
19/46
Invoking Methods With Arguments
To pass arguments from one method to another, include the
arguments in the parentheses of the method call.
List the arguments in the same order in which they are listed
in the declaration of the worker method and pass all
required arguments.
The compiler checks to see if the type, order and number of
the parameters passed matches the type, order and numberof the parameters a mehod accepts
7/30/2019 Topic 3 Part 1 Method
20/46
Declare Methods With Return Value
Syntax :
[modifier] data_type
identifier(parameters_list)
{//line of code}
E.g :
public int sum(int numOne, int numTwo)
{//line of code}
A method can return only ONE value but can
accept multiple arguments
7/30/2019 Topic 3 Part 1 Method
21/46
Returning a Value
To return a value from a method, use the
return keyword.
For example, the following code returns the
current value held in the sum variable.public int sum(int numOne, int numTwo) {
int result=numOne + numTwo;
return result;}
7/30/2019 Topic 3 Part 1 Method
22/46
Advantages of Method Use
1. Make program more readable and easier to maintain
Easy to configure out what a program is doing if the code is dividedamong several different methods with names that match thebehavior of the methods
2. Make development and maintenance quicker.
You can choose to create and test the program one method at a timeto ensure that the program, as a whole will work when it is finished.
3. Central to reusable software
The Java technology class libraries have many classes withmethods that you can use over and over again in yourprogram.
4. Allow separate objects to cmmunicate and to distributethe workperformed by the program
A method in one object can invoke a method in another object. Theobject can pass the method information and receive a return value.
7/30/2019 Topic 3 Part 1 Method
23/46
Passing Parameters
There are two ways of passing parameters
to a method.
They are:
Pass-by-value
Pass-by-reference
7/30/2019 Topic 3 Part 1 Method
24/46
Pass by Value
When parameters are passed by value, only
the value of the variable is passed to the
method.
Any change made to the variable in thecalled method will not affect the variable in
the calling method.
7/30/2019 Topic 3 Part 1 Method
25/46
public class value{public static void main(String args[]){int A=5,B=7;System.out.println("Before calling the method:");
System.out.println("A = " + A);System.out.println("B = " + B);change(A,B);System.out.println("After calling the method:");System.out.println("A = " + A);System.out.println("B = " + B);System.out.println("\nThis is pass by value");}
static void change(int A,int B){A=2;B=3;}
}
7/30/2019 Topic 3 Part 1 Method
26/46
When the Function is called
1001 A 1050 B
1100 A 1155 B
5 7
5 7
After returning to main
1001 A 1050 B
1100 A 1155 B
5 7
2 3
Before calling the Function
1001 A 1050 B
5 7
Memory
Address
Variable
Name
Value
7/30/2019 Topic 3 Part 1 Method
27/46
Pass by Reference
When parameters are passed by reference,
the address of the variable is passed to the
method.
Any change made to this variable in thecalled method will affect the variable in the
calling method.
7/30/2019 Topic 3 Part 1 Method
28/46
public class Reference{public static void main(String args[]){int[] arr={5,7};
System.out.println("Before calling the method:");
System.out.println("arr[0] = " + arr[0]);System.out.println("arr[1] = " + arr[1]);
change(arr);System.out.println("After calling the method:");System.out.println("arr[0] = " + arr[0]);System.out.println("arr[1] = " + arr[1]);System.out.println("This is pass by reference");
}
static void change(int num[]){num[0]=2;num[1]=3;
}}
7/30/2019 Topic 3 Part 1 Method
29/46
When the Function is called
1001 arr[0] 1050 arr[1]
num[0] num[1]
5 7
Before calling the Function
1001 arr[0] 1050 arr[1]
5 7
Memory
Address
Array Name
Value
After returning to main
1001 arr[0] 1050 arr[1]
num[0] num[1]
2 3
7/30/2019 Topic 3 Part 1 Method
30/46
Creating static Methods and Variables
Methods and variables that are unique to an instance
are called instance methods and instance variable
Using methods thst do not require object
instantiation, such as main method. These are called
class methods or static method. You can invoke themwithout creating an objectfirst.
Java programming language allows you to create
static variables or class variables, which you can use
without creating an object.
The main method is a static method that you have
already used. You do not have to create object
instance to use the main method.
7/30/2019 Topic 3 Part 1 Method
31/46
Declare Static Method
Declare using static keyword.
E.g :
static Properties getProperties()
7/30/2019 Topic 3 Part 1 Method
32/46
Invoking static Method
Static or class methods are not part of any
object instance (just the class), you should
not use an object reference variable to
invoke them.
Instead, use the class name. the syntax for
invoking a static method is :
Classname.method();
Shirt.getDetail();
7/30/2019 Topic 3 Part 1 Method
33/46
Declare static Variable
Use the static keyword to declare that there
can only be one copy of the variable in
memory associated with a class, not a copy
for each object instance.
E.g :
static double saleTax=8.25;
7/30/2019 Topic 3 Part 1 Method
34/46
Accessing static Variable
Use the class name to access a static variable.
The syntax for invoking a static variable is :
Classname.variable;
For example, to access the value the static variablefor PI in the Math class :
double myPI;
myPI=Math.PI;
Variables can have both the static and final modifierto indicate that there is only one copy of the variableand that the contents of the variable cannot bechange. The PI variable in the Math class is a staticfinal variable.
7/30/2019 Topic 3 Part 1 Method
35/46
Polymorphism
Polymorphism is the existence of an entityin many forms. In object oriented
programming language it refers to the
ability of the objects to behave differently
based on the input given.
Polymorphism is implemented in Java usingtechniques:
Method Overloading
Constructor Overloading.
7/30/2019 Topic 3 Part 1 Method
36/46
Method Overloading
Two or more methods having the samename but different signature.
Methods which have same name but
different parameters are called asoverloaded methods.
The parameters in overloaded methodsshould differ in at least one of the following:
Number of parameters
Data type of the parameters
7/30/2019 Topic 3 Part 1 Method
37/46
Observe the program
class Poly
{
public static void main(String args[])
{
Over obj=new Over();obj.display();
obj.display(2);
obj.display("Kuala lumpur is theGarden city of lights",3);
}
}
7/30/2019 Topic 3 Part 1 Method
38/46
class Over
{
void display()
{
System.out.println("Melaka is ahistorical state");
}
7/30/2019 Topic 3 Part 1 Method
39/46
void display(int i)
{
int j=0;
while(j
7/30/2019 Topic 3 Part 1 Method
40/46
void display(String str,int i)
{
for (int j=1;j
7/30/2019 Topic 3 Part 1 Method
41/46
void display(int i)
{
int j=0;
while(j
7/30/2019 Topic 3 Part 1 Method
42/46
Constructor Overload
The concept of having two or moreconstructors with different signature in the
same class is called Constructor Overloading.
Two or more constructors in a class withsame name and different parameters are
called as overloaded constructors.
7/30/2019 Topic 3 Part 1 Method
43/46
Observe the program
class c_o_load
{
public static void main(String args[])
{
volume vol1=new volume(4);
volume vol2=new volume(4,6);
vol1.sphere();
vol2.cylinder();
}
}
7/30/2019 Topic 3 Part 1 Method
44/46
class volume{
double r,h;
volume(double r)
{
this.r=r;
}
volume(double r,double h)
{
this.r=r;
this.h=h;
}
7/30/2019 Topic 3 Part 1 Method
45/46
void sphere()
{
double vol;
vol=4/3*3.14*r*r*r;
System.out.println("The volume ofSphere is " + vol);
}
7/30/2019 Topic 3 Part 1 Method
46/46
void cylinder()
{
double vol;
vol=3.14*r*r*h;
System.out.println("The volume ofcylinder is " + vol);
}
}//end of class