Download Collaboration Between Objects

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Java the UML Way
http://www.tisip.no/JavaTheUmlWay/
Collaboration Between Objects
Collaboration between objects
Collaboration in the renovation case
The getNoOfMeters() method with sequence diagram
The getTotalPrice() method
Collaboration beween objects of the same class
The renovation case, a menu-driven program
Several references to the same object
Passing arguments
version 2000-04-17
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
page 2
page 3-4
page 5-6
page 7
page 8-9
page 10-13
page 14-18
page 19-20
Chapter 7
Collaboration Between Objects
• In reality objects often collaborate to solve tasks. Examples:
– The teacher sends the message “Complete this task” to a student. The
student searches for help from other students, and searches on the Internet
or in books to complete the task.
– Elisabeth turns her CD player on. It has to collaborate with the CD to be
able to make music.
• In programs, we get an object to collaborate with another object by
sending messages to it. Example: We send the message “Play this
CD!” to the myCDplayer object in this way:
– myCDplayer.play(“Four Seasons”);
• For an object to send messages to other objects, it must have access to
the other objects.
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 7, page 2
Class Diagram, the Renovation Case
Paint
Wallpaper
Surface
Flooring
name
length
width
name
price
widthOfFlooring
name
price
noOfCoats
noOfSqMPerLiter
name
price
lengthPerRoll
widthPerRoll
getName
getLength
getWidth
getArea
getCircumference
getName
getPricePerM
getWidth
getNoOfMeters
getTotalPrice
getName
getPricePerLiter
getNoOfCoats
getNoOfSqMPerLiter
getNoOfLiters
getTotalPrice
getName
getPricePerRoll
getLengthPerRoll
getWidthPerRoll
getNoOfRolls
getTotalPrice
•
•
An instance of the Flooring class has to collaborate with an instance of the
Surface class to calculate the number of meters required to cover the surface.
The Paint and Wallpaper objects have to collaborate with the Surface object to
calculate the number of liters and rolls, respectively.
Sorce code for the classes: Surface, page 86, Flooring and Wallpaper, page 182-184. (Paint, solution to
problem 2 p. 189.)
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 7, page 3
Collaboration, Examples
The client
instantiates two
objects
Message to the flooring:
How many meters do we
need of you to cover the
surface?
Message to the flooring:
What will it cost to cover
the surface with you?
class FlooringClient {
public static void main(String[] args) {
Surface theSurface = new Surface("Margaret's Floor", 5, 6);
Flooring theFlooring = new Flooring("Fitted carpet", 24.50, 5);
double noOfMeters = theFlooring.getNoOfMeters(theSurface);
double price = theFlooring.getTotalPrice(theSurface);
System.out.println("You need " + noOfMeters +
" meters, price $" + price);
}
}
Printout: You need 6.0 meters, price $147.0
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 7, page 4
The getNoOfMeters() Method
public double getNoOfMeters(Surface aSurface) {
double lengthSurface = aSurface.getLength();
double widthSurface = aSurface.getWidth();
int noOfWidths = (int)(lengthSurface / widthOfFlooring);
double rest = lengthSurface % widthOfFlooring;
if (rest >= limit) noOfWidths++;
return noOfWidths * widthSurface;
}
•
•
•
•
The method call: double noOfMeters = theFlooring.getNoOfMeters(theSurface);
A reference to the surface object is sent along with the message. (As an argument to
the method.)
In this way the method gets access to the client's surface object.
And, because of that, the method may send messages to the surface object.
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 7, page 5
The Collaboration is Shown by This Sequence Diagram
underlining
indicates objectname
”client”
time
the client
instantiates
theFlooring and
theSurface
the client tells
theFlooring to
calculate the no. of
meters needed to
cover theSurface
new
new
theFlooring
getNoOfMeters(theSurface)
getLength()
theFlooring asks
theSurface about
the length and the
width,
and will then be
able to calclulate
the number of
meters needed
theSurface
getWidth()
sending a
message
Solve problem 1,
page 189.
object in
activity
response
from message
(return value)
the objects’
lifeline
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 7, page 6
The getTotalPrice() Method
public double getTotalPrice(Surface aSurface) {
return getNoOfMeters(aSurface) * price;
}
The method call:
double price = theFlooring.getTotalPrice(theSurface);
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 7, page 7
Two Objects of the Same Class Collaborate
Example: Comparing areas
Surface surface1 = new Surface("A", 5, 4);
Surface surface2 = new Surface("B", 4, 4);
int result = surface1.compareAreas(surface2);
if (result < 0) System.out.println(surface1.getName() + " is the smaller one.");
else if (result > 0) System.out.println(surface2.getName() + " is the smaller one.");
else System.out.println("The surfaces have the same area.");
Here is the compareAreas() method in the Surface Class:
public int compareAreas(Surface theOtherSurface) {
final double precision = 0.00001;
double area1 = getArea();
double area2 = theOtherSurface.getArea();
if (Math.abs(area2 - area1) < precision) return 0;
else if (area1 < area2) return -1;
else return 1;
}
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 7, page 8
Two Surface-Objects Collaborate to Find the Larger
”client”
the client
instantiates
surface1 and
surface2
the client
tells surface1
to compare
itself to
surface2
surface1 asks
itself about its
own area,
then it asks
surface2 about
its area
new
surface1
new
compareAreas(surface2)
surface2
getArea()
getArea()
then surface1
compares the
areas and
returns the
result of the
comparison
Solve problem 3, page 189-190.
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 7, page 9
A Menu-Driven Program
We'll calculate the materials required and the price for renovating a surface (wall or floor).
show instructions to the user
let the user do a menu choice
[option == exit]
[option != exit]
carry out the chosen task
let the user do a menu choice
public static String[] alternatives =
{"Wallpaper", "Paint", "Flooring", "Exit"};
JOptionPane.showOptionDialog(null,
"What do you choose:", "Renovation",
JOptionPane.DEFAULT_OPTION,
JOptionPane.PLAIN_MESSAGE, null,
alternatives, alternatives[0]);
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 7, page 10
Which Classes Do We Need?
•
•
Of course, the Surface, Flooring, Paint and Wallpaper classes.
We need an object that can be responsible for carrying out the tasks in the
activity diagram:
–
–
–
•
•
Display a short instruction to the user.
Input a menu choice from the user.
Carry out the chosen task
We call this class ProjectChap7GUI.
Do we need even more classes? Let us look at, for example, how the paint
requirement has to be calculated:
1. Input data about the surface that will be painted (name, length, width).
2. Create an instance of the Surface class.
3. Input data about the paint that will be used (name, price, number of coats, number
of square meters per liter).
4. Create an instance of the Paint class.
5. Ask the paint object how much paint is needed to cover the given surface and what
it will cost.
6. Output the answers.
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 7, page 11
The ReaderRenovationCase Class
• Points 1 and 3 generate much use of JOptionPane to input data 
many code lines loosing overview
• Points 1 and 2, and points 3 and 4, are general tasks that may be useful
in other situations.
• We compose a new class with methods for inputting information and
instantiating objects: ReaderRenovationCase
ProjectChap7
details::
ReaderRenovationCase
alternativs[1..* ]: String
showInstructions()
doAChoice(): int
carryOutTheRightThing(
option: int)
ReaderRenovationCase
readAndInstantiateSurface
readAndInstantiateWallpaper
readAndInstantiatePaint
readAndInstantiateFlooring
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 7, page 12
Show the Source Code,
Program Listings 7.2 and 7.3 (pages 194-197)
Solve problem 2, pp. 193-194.
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 7, page 13
Several References to the Same Object
• Collaboration between objects usually means that we have several
references to the same object.
• It can be difficult to keep track of this if the references are in different
methods or perhaps even in different classes.
• Which kinds of problems may arise?
• We’ll look at two concrete examples:
– An access method gains access, via the parameter list, to an object that
“belongs” to the client.
– An instance variable refers to an object that it has received via the
parameter list for a constructor or a mutation method. The object is
created by the client.
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 7, page 14
A Reference Type as a Parameter for an Access Method
Flooring theCarpet = new Flooring("AutumnBrown", 23.50, 5.0);
Surface myFloor = new Surface("Anne’s floor", 4.2, 3.5);
theCarpet
myFloor
”AutumnBrown”
23.50
5.0
”Anne’s floor”
4.2
3.5
Here is a new reference
to the floor-object
aSurface
double noOfMeters = theCarpet.getNoOfMeters(myFloor);
What happens when the method
getNoOfMeters() is invoked?
Behind the scenes:
Surface aSurfacethe method = myFloorclient;
public double getNoOfMeters(Surface aSurface) {
double lengthSurface = aSurface.getLength();
double widthSurface = aSurface.getWidth();
……
}
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 7, page 15
A Reference Type as a Parameter for an Access Method,
continued
• What may happen inside getNoOfMeters()?
• If the Surface class is mutable, the method may change the data inside
the Surface object, which is an object "belonging" to the client.
Starting point:
myFloor
(the client)
”Anne’s floor”
4.2
3.5
aSurface
(parameter in the
getNoOfMeters() method)
What may happen inside the method:
aSurface.setLength(5.7);
myFloor
(the client)
”Anne’s floor”
5.7
3.5
aSurface
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 7, page 16
An Instance Variable Refers to an Object that is Created
by the Client
• The Surface class is expanded with information about the flooring which will be
used.
• New constructor:
public Surface(String initName, double initLength, double initWidth, Flooring initFlooring) {
name = initName;
the server object
length = initLength;
the client’s
myFloor’s
width = initWidth;
reference
reference
flooring = initFlooring;
AutumnBrown
theCarpet
flooring
5.0
}
• The client program instantiates objects:
23.50
Flooring theCarpet = new Flooring("AutumnBrown", 23.50, 5.0);
Surface myFloor = new Surface("Anne’s floor", 4.2, 3.5, theCarpet);
• As an alternative, the constructor may create a copy of the flooring object:
flooring = new Flooring(initFlooring.getName(),
initFlooring.getPrice(), initFlooring.getWidth());
• Now, the client and the myFloor object will each have one copy of the flooring
object.
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 7, page 17
Several References to the Same Object, Conclusion
• Keep the number of classes having access to a mutable object at a
minimum – minimal coupling between classes.
• Consider using immutable classes. Instead of changing the object, a
new object is made (The String class is a well known example.)
• Several classes may work with one copy each, but that seldom agree
with the reality modeled.
We have to know what we do,
and we should document well.
Solve problem 1, pp. 201-202.
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 7, page 18
Passing Arguments
•
•
•
We’ve seen that a method can change an object On the client side before the method invoking:
that “belongs” to the client, if a reference to the
object is an argument to the method.
”Margaret's flooring”
Can a method, in a similar fashion, change a
24.50
variable of a primitive data type?
theFlooring
5
As an example, we expand the Flooring class
with the following method that change the price newPrice
18.50
of the flooring:
public void setPrice(double newPrice) {
price = newPrice;
newPrice = 0.0;
}
•
Behind the scenes when invoking the setPrice() method:
double newPricethe method = newPriceclient;
At the client side:
Flooring theFlooring = new Flooring(
"Margaret's flooring", 24.50, 5);
String newPriceRead =JOptionPane.
showInputDialog("New price: ");
double newPrice = Double.
parseDouble(newPriceRead);
theFlooring.setPrice(newPrice);
The method’s own variable:
newPrice
18.50
The method zeroes this variable:
newPrice
0.0
No changes on the client side.
No changes on the client side.
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 7, page 19
Summary, Argument Passing
•
•
•
In a method call, the values for the arguments are always passed.
The parameters are to be used as local variables, with initial values equal to the
argument values.
We differentiate between the following two cases:
– The parameter is of a primitive data type: if the method changes the value for this
variable, that doesn’t affect the argument at all.
– The parameter is a reference: a copy of the argument means that the method and the
client each have their own reference to the same object. If the method makes
changes to the object, they will, of course, apply to the object that the argument
points to, since that’s the same object we’re talking about.
arguments
The call: aObject.doSomething(10, theSurface);
Method: void doSomething(int number, Surface aSurface) {
….
parameters
}
Solve all problems, page 204.
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
”Ceiling”
3
5
theSurface
aSurface
number
10
Chapter 7, page 20