0% found this document useful (0 votes)
17 views32 pages

05 PassingObjects

Uploaded by

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

05 PassingObjects

Uploaded by

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

5.

Passing Arguments to
Methods
Method
• A method is a collection of statements that are
grouped together to perform an operation.
• A method is always defined inside a class.
• Method signature or method header is the
combination of the method name and the
parameter list.

Method definitions have the form

method header {
method body
}
2
Parts of a Method Header
Method Return Method Parentheses
Modifiers Type Name

public int getEmpNum ()


{

return empnum;

}
The above method is an instance method.
The type of result returned is returnType where int means the method
returns an integer result.

3
Parts of a Method Header
Method Return Method Parentheses
Modifiers Type Name

public void setEmpNum (int num)


{

empnum = num;

}
The above method is an instance method.
The type of result returned is returnType where void means the
method does not return a result.

4
return Statement

 A method, unless void, returns a value of the


specified type to the calling method.
 The return statement is used to immediately
quit the method and return a value:
return expression;

The type of the return


value or expression
must match the
method’s declared
return type.
5
return Statement (cont’d)
 A method can have several return
statements; then all but one of them must be
inside an if or else (or in a switch):
public someType myMethod (...)
{
...
if (...)
return <expression1>;
else if (...)
return <expression2>;
...
return <expression3>;
}
6
return Statement (cont’d)
 A boolean method can return true, false,
or the result of a boolean expression:
public boolean myMethod (...)
{
...
if (...)
return true;
...
return n % 2 == 0;
}

7
Calling an instance method
 A method executes when it is called.
 The main method is automatically called when a
program starts, but other methods are executed
by method call statements
 A method with a non-void return value type can
also be invoked as a statement.
 An invocation of an instance method that returns
an integer value may use an assignment
statement or output statement:
int vnum;
vnum = obj1.getEmpNum();
or
System.out.println ("employee num:" +
8
obj1.getEmpNum());
Calling an instance method
 An invocation of a void instance method is
simply a statement:
objectName.methodName();
 Example:
obj1.setEmpNum(123);

9
Passing Parameters to Constructors
 Any expression that has an appropriate
data type can serve as a parameter:
public static void main (String[] args) {
Employee emp1 = new Employee();
Employee emp2 = new Employee(123); // argument
Employee emp3= new Employee(456, "Ahmad"); // argument
}
public class Employee {
public Employee () { }
public Employee (int num) { // parameters
empnum = num ;}
public Employee (int num, String name) {
empnum = num ;
empname = name;
} 10
Passing Arguments to a Method
 Values that are sent into a method are called
arguments.
System.out.print("Input the employee number:");
number = Integer.parseInt(str);
obj1.setEmpNum(number);
 The data type of an argument in a method call
must correspond to the variable declaration in the
parentheses of the method declaration. The
parameter is the variable that holds the value
being passed into a method.

5-11
Arguments are Passed by Value
 In Java, all arguments of the primitive data
types are passed by value, which means that
only a copy of an argument’s value is passed
into a parameter variable.
 Any change to a parameter variable inside a
method, has no affect to the original argument.

5-12
Passing Parameters : primitive type

 Primitive data types are always passed “by


value”: the value is copied into the parameter.
public class Employee
{
int x = 123; ... copy
emp1.setEmpNum ( x ); public void setEmpNum (int num)
{
empnum = num;
num acts like a
...
local variable in
}
setEmpNum
}

x: 123 copy num: 123


13
Passing Parameters (cont’d)
public class Test
{
public double square (double x)
{
x *= x; x here is a copy of the parameter
return x; passed to square. The copy is
} changed, but...

public static void main(String[ ] args)


{
Test calc = new Test (); ... the original x
double x = 3.0; is unchanged.
double y = calc.square (x); Output: 3 9
System.out.println (x + " " + y);
}
} 14
Passing Objects as Arguments
 Objects can be passed to methods as
arguments.
 Java passes all arguments by value.
 When an object is passed as an argument,
the value of the reference variable is passed.
 The value of the reference variable is an
address or reference to the object in memory.
 When a method receives a reference variable
as an argument, it is possible for the method
to modify the contents of the object
referenced by the variable.
15
Passing Object As Arguments to
Methods
public class Rectangle { public double getWidth() {
private double width; return width;
private double length; }

public Rectangle (double w, public double getLength() {


double l) { return length;
width = w; }
length = l;
} public double calcArea() {
return width * length;
public void setWidth(double w) { }
width = w;
} public boolean equals(Rectangle r) {
return (this.calcArea() == r.calcArea());
public void setLength(double l) { }
length = l; } 16
}
Passing Object As Arguments to
Methods
1. public class PassObject {
2. public static void main(String[ ] args) {
3. Rectangle box1 = new Rectangle(12.0, 5.0);
4. Rectangle box2 = new Rectangle(10.0, 8.0);
5. if (box1.equals(box2))
6. System.out.println ("Yes, it's equals");
7. else
8. System.out.println ("No, it's not equal");
9. }
10. }

Line 3 and 4 creates two instances of Rectangle class.


Line 5 the value of the variable box2 (reference variable of Rectangle) is
passed as an argument to the instance method, equals().
In Rectangle class, equals() method has a parameter, r, which is a
Rectangle reference variable and return a boolean value, after comparing 17

whether the two objects are equal.


Passing Objects as Arguments
A Rectangle object

length: 12.0
width: 5.0
box1.equals(box2);

Address

public boolean equals(Rectangle r)


{
return (this.calcArea() == r.calcArea());
}

18
Returning Objects From Methods
import java.util.*;
public Rectangle inputRectangle() {
public class PassObject3 { Scanner inp = new Scanner (System.in);
double newWidth, newLength;
public static void main(String[ ] args) {
Rectangle box3 = new System.out.print ("Enter width : ");
Rectangle().inputRectangle(); newWidth = inp.nextDouble();
System.out.println (“The area: “ + System.out.print ("Enter length : ");
box3.calcArea()); newLength = inp.nextDouble();

} return new Rectangle(newWidth, newLength);


}
}

19
Returning Objects From Methods
 Methods can return references to objects.
 Just as with passing arguments, a copy of the
object is not returned, only its address.
 Method return type:

public Rectangle inputRectangle ()


{

return new Rectangle(newWidth, newLength);
}

20
The FoodItem class
The class diagram that represents a food item at a market

UML class diagram

FoodItem
- description: String
- size: double
- price: double
+ FoodItem()
+ setDesc()
+ setSize()
+ setPrice()
+ getDesc()
+ getSize()
+ getPrice()
+ calcUnitPrice()
+ toString()

21
Methods for Class FoodItem
 For most classes, we need to provide methods that perform
tasks similar to the ones below.
 a method to create a new FoodItem object with a specified
description, size, and price (constructor)
 methods to change the description, size, or price of an existing
FoodItem object (mutators)
 methods that return the description, size, or price of an existing
FoodItem object (accessors)
 a method that returns the object state as a string (a
toString() method).

22
Method Headers for
Class FoodItem
Method Description
public  Constructor - creates a new
FoodItem(String, object whose three data fields
double, double) have the values specified by its
three arguments.
 Mutator - sets the value of data
public void
field description to the value
setDesc(String)
indicated by its argument.
Returns no value.
public void  Mutator - sets the value of data
setSize(double) field size to the value indicated
by its argument. Returns no
value.

23
Method Headers for
Class FoodItem, cont’d.
Method Description
public void  Mutator - sets the value of data
setPrice(double) field price to the value
indicated by its argument.
Returns no value.
public String  Accessor - returns a reference
getDesc() to the string referenced by data
field description.

public double  Accessor - returns the value of


getSize() data field size.

24
Method Headers for
Class FoodItem, cont’d.
Method Description
public double  Accessor - returns the value
getPrice() of data field price.

public String  Returns a string representing


toString() the state of this object.

public double  Returns the unit price (price /


calcUnitPrice() size) of this item.

25
Class FoodItem
/*
* FoodItem.java
* Represents a food item at a market
*/
public class FoodItem {

// data fields
private String description;
private double size;
private double price;

26
Class FoodItem, cont’d.

// methods
// postcondition: creates a new object with data
// field values as specified by the arguments
public FoodItem(String desc, double aSize,
double aPrice) {
description = desc;
size = aSize;
price = aPrice;
}

// postcondition: sets description to argument


// value
public void setDesc(String desc) {
description = desc;
}
27
Class FoodItem, cont’d.
// postcondition: sets size to argument value
public void setSize(double aSize) {
size = aSize;
}

// postcondition: sets price to argument value


public void setPrice(double aPrice) {
price = aPrice;
}

// postcondition: returns the item description


public String getDesc() {
return description;
}

// postcondition: returns the item size


public double getSize() {
return size;
} 28
Class FoodItem, cont’d.
// postcondition: returns the item price
public double getPrice() {
return price;
}

// postcondition: returns string representing


// the item state
public String toString() {
return description + ", size : " + size +
", price $" + price;
}

// postcondition: calculates & returns unit price


public double calcUnitPrice() {
return price / size;
}
}

29
Testing the class FoodItem
UML class diagram

client TestFoodItem
(application) class
main()
association
relationship

worker FoodItem
class description: String
size: double
price: double
FoodItem()
setDesc()
setSize()
setPrice()
getDesc()
getSize()
getPrice()
calcUnitPrice()
toString()

Program classes and their relationships 30


Application or Client of FoodItem
/*
* TestFoodItem.java
* Tests class FoodItem
*/
public class TestFoodItem {

public static void main(String[] args) {


FoodItem myCandy = new FoodItem("Snickers", 6.5,
0.55);
FoodItem mySoup = new FoodItem(
"Progresso Minestrone",
16.5, 2.35);
System.out.println(myCandy.toString());
System.out.println(" -- unit price is $" +
myCandy.calcUnitPrice());
System.out.println(mySoup.toString());
System.out.println(" -- unit price is $" +
mySoup.calcUnitPrice());
}
}
31
Sample Run of Class
TestFoodItem

32

You might also like