Download Parameters - SRU Computer Science: Welcome!

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
PARAMETERS
• Making Messages Specific
• Setting Up Associations
• Actual and Formal Parameters
• Return Types
• Accessor and Mutator Methods
Problem 1: Making Messages Specific
• CSMobile needs a paint job!
• Let’s say we want to give CSMobile the
capability of being painted different colors
• One solution:
– add a method to CSMobile for each color we want to
paint with
public void setRed();
public void setBlue();
public void setTeal();
public void setMauve();
...
• Not very elegant to write all these methods
• Much more efficient to write one setColor
method in class CSMobile in which we could
specify the color that we want to paint with
• How do we make a message specific?
Parameters
2 of 32
© 2006 Pearson
Education
Problem 2: A Smart CSMobile
• CSMobile is going for a drive!
• It’s time to associate CSMobile with the City
it’s driving in
– so that it can call methods on class City to ask
where schools and parks are located
• Remember, City contains CSMobile
– City can automatically call methods on CSMobile
• But containment relationship is not symmetric
– CSMobile can’t automatically call methods on City
• So how can we enable CSMobile to know its
container, City, so it can call methods on
City?
• Need to associate a City instance with a
CSMobile instance in order for a CSMobile
to call methods on City.
• How do we associate two objects?
Parameters
3 of 32
© 2006 Pearson
Education
Parameters
• Answer: Parameters!
• We use Parameters in 2 cases:
1) To make messages between objects specific
by sending additional information
– in a setColor() method, we can specify color
– in an eat() method, we can specify food
2) For one object to learn about
another object that it didn’t create
– can use a method to let a CSMobile know about the
City it is driving in
– this is the way to set up association (“knows-about”)
relationships
• But how?
Parameters
4 of 32
© 2006 Pearson
Education
Sending and Receiving
• A sending method sends specifics of a given
situation to a receiving method
specifics
green
receiving
setColor()
method
• This is what the parentheses after the method
names are for
– parameters are variables that go inside the
parentheses
• In fact, you already know parameters quite
well
– a function in math is like a method that receives one
or more parameters and computes a result
– “send” the function a specific value of the parameter
– example:
2
specific value
Parameters
f(x) = x2 + 2x + 5
receiving function
5 of 32
© 2006 Pearson
Education
Formal and Actual Parameters
• x is a Formal parameter
– formal parameters are “dummy” variables that
represent instances sent when calling a method
– have no value of their own; take on value of
parameters passed in when method is called
– placeholders, like x in x2 + 2x + 5
• 2 is an Actual parameter
– actual parameters are “actual” instances sent when
calling method
– specific values passed with message from sender to
receiver
2
f(x) = x2 + 2x + 5
actual parameter formal parameter
13
returns
• Let’s see a method that receives parameters!
Parameters
6 of 32
© 2006 Pearson
Education
Syntax: The Receiver
/**
* This class models a CSMobile that
* can be painted any color. The instance
* variables and other methods that we defined
* in earlier lectures are elided for brevity.
*/
public class CSMobile {
private java.awt.Color _color;
// other instance variable declarations elided
public CSMobile() {
_color = java.awt.Color.white; // default
// other instance variable definitions elided
}
public void setColor( java.awt.Color newColor ){
_color = newColor;
// now paint the car using the color
// we have stored in _color
}
formal parameter
// other methods elided
}
Parameters
7 of 32
© 2006 Pearson
Education
Syntax: The Sender
/**
* This simple App only sends the CSMobile’s
* brand new setColor method a parameter.
*/
public class SimpleApp extends
wheels.users.Frame {
private CSMobile _csMobile;
public SimpleApp() {
_csMobile = new CSMobile();
_csMobile.setColor( java.awt.Color.blue );
}
actual parameter
public static void main ( String[] argv ) {
SimpleApp app = new SimpleApp();
}
}
Parameters
8 of 32
© 2006 Pearson
Education
Syntax for the Receiver
• Syntax for class CSMobile:
private java.awt.Color _color;
– java.awt.Color is the built-in Java class that
represents a color
– CSMobile has an instance variable representing its
color, set in its constructor
_color = java.awt.Color.white; // default
– java.awt.Color.white is a constant
– java.awt.Color class has many predefined
constant colors which are public instance variables of
the Color class (examples: red, green, blue,
white)
– okay for them to be public instance variables
because they are constant (cannot be changed!) so
don’t need to worry about value changing
unexpectedly
– more on how you can create constants later in the
course
Parameters
9 of 32
© 2006 Pearson
Education
More Syntax for the Receiver
public void setColor( java.awt.Color newColor ) {
type
that method expects
formal parameter (name)
– example of a method that receives a parameter
– parameter is of type java.awt.Color
• tells Java that this method “takes in” an instance of the
java.awt.Color class when it is called
– newColor is a formal parameter
• a.k.a. the name that the parameter will be referred to
in this method
• can only use newColor within setColor() method
– a method that receives one parameter is always
of the form
methodName(param-type param-name)
• we often record the parameter in an instance
variable
_color = newColor;
read: _color “gets” the same Color
as newColor (i.e., whatever value
newColor was set to by sender)
Parameters
10 of 32
© 2006 Pearson
Education
Syntax for the Sender
• Syntax for class SimpleApp:
_csMobile.setColor( java.awt.Color.blue );
actual parameter
(value)
– example of a method call that sends a parameter
– here, we send the constant java.awt.Color.blue
as an actual parameter to the receiving method,
setColor()
– note: don’t specify the type of the parameter you
“pass in” (in this case, java.awt.Color)
• this is because the parameter type is already specified
in the CSMobile class
• if you tried to pass in something that wasn’t a Color,
you would get a compile error like:
Incompatible type for method.
Can’t convert somethingBad to Color.
Parameters
11 of 32
© 2006 Pearson
Education
More on Actual and Formal Parameters
• One-to-one correspondence between formal
and actual parameters
– order, type (class) of instances, and number of
parameters sent must match order, type, and number
declared in method!
_csMobile.setColor(java.awt.Color.blue)
• sends one parameter of type java.awt.Color
matches
public void setColor( java.awt.Color newColor )
• expects one parameter of type java.awt.Color
• Name of formal parameter does not have to
be the same as the corresponding actual
parameter
– receiver cannot know what specific instances will be
passed to it, yet it must know how to refer to it
• so receiver uses a dummy name to represent the
parameter
– sender may send different actual parameters
• may send red, blue, yellow, etc. to setColor()
method
Parameters
12 of 32
© 2006 Pearson
Education
Signatures
• The combination of the
method identifier,
the class of its parameters,
and the order of its parameters
is called the method’s signature.
– Like a person’s signature, a method’s signature must
be unique.
– Trying to provide two methods in one class with the
same signature will cause an error like:
duplicateMethod() is already defined
in MyClass:
public void duplicateMethod();
Parameters
13 of 32
© 2006 Pearson
Education
References as Values of Variables
• To send messages to an object, we must have
a name for it
– in Java, can only access objects via references to
them
• Objects do not contain actual component
objects, only references to them
_color
refers to an
instance of
java.awt.Color
• The equals operator actually assigns
references
_csMobile = new CSMobile();
makes _csMobile refer to a new instance
of class CSMobile
• i.e., _csMobile is assigned a reference to an
instance created by CSMobile()
_color = newColor;
makes _color refer to the same instance of Color
class that newColor does
• i.e., _color is assigned the same color as newColor
Parameters
14 of 32
© 2006 Pearson
Education
Review: References Revealed
• References are just pointers to memory
– human readable versions of addresses
– easier to keep track of names than weird numbers
(like 0xeff8a9f4)
– holds memory address where instance is stored
– Java also has primitives, which are not objects and
do not have pointers (more on this later)
reference to
instance 1
Parameters
reference to
instance 2
15 of 32
reference to
instance 3
© 2006 Pearson
Education
Parameters as References
• Formal parameters refer to the same instance as
actual parameters after the method is called
– i.e., they are different names for the same instance
– so, calling a method on instance referred to by formal
parameter is the same as calling the method on
instance referred to by actual parameter (not the
same as in some other programming languages!)
S
E
N
D
E
R
public class SimpleApp {
...
Actual parameter
_csMobile.setColor(java.awt.Color.blue);
...
}
java.awt.Color
R
E
C
E
I
V
E
R
public class CSMobile {
...
public void setColor(java.awt.Color newColor) {
...
}
Formal parameter
}
Parameters
16 of 32
© 2006 Pearson
Education
Parameters and Association
• Finally, the moment you’ve all been waiting
for...
• Let’s use what we’ve learned about
parameters to enable a CSMobile to know
about its City -- called association
– CSMobile can store a reference to its City so that it
can send messages to it
• Usually associations are done in the
constructor
– don’t forget that constructors are methods, too
– they can receive parameters just like any other
method
• Let’s see all this in action...
Parameters
17 of 32
© 2006 Pearson
Education
Syntax: The Receiver
/**
* This class models a CSMobile that
* knows about its City. Again, the instance
* variables, constructor, and other
* methods that we defined in earlier
* slides are elided.
*/
public class CSMobile {
private City _city;
public CSMobile(City myCity) {
_city = myCity;
}
}
So whoever instantiates a CSMobile is expected to pass
in a City to the CSMobile’s constructor for the
CSMobile to be associated with. This City will be
temporarily referenced by the formal parameter myCity
which is then permanently assigned to the instance variable
_city. Now the CSMobile can call methods on the
City .
Parameters
18 of 32
© 2006 Pearson
Education
Syntax: The Sender
/**
* This class models a city
* where CSMobiles exist. Because the
* City contains the CSMobile, it can
* send the CSMobile the reference to
* an instance of itself.
*/
public class City {
private CSMobile _csMobile;
public City() {
_csMobile = new CSMobile(this);
}
}
In this case, the “whoever” mentioned on the previous slide
is the City itself. It passes the CSMobile a reference to
itself by using the reserved word this. Now _csMobile
is associated with “this” instance of City .
Parameters
19 of 32
© 2006 Pearson
Education
Syntax for the Receiver
• Syntax for class CSMobile:
private City _city;
– CSMobile has a variable representing the City that
it is driving in
// CSMobile constructor
public CSMobile( City myCity ) {
_city = myCity;
}
– standard constructor that receives a parameter
– assigns the parameter passed in, myCity, to the
instance variable, _city
– CSMobile now knows about myCity
Parameters
20 of 32
© 2006 Pearson
Education
Syntax for the Sender
• Syntax for class City:
_csMobile = new CSMobile( this );
• Remember this
(“Making Objects” lecture, slide 23)?
– shorthand for “this instance”, i.e., instance of the
class where execution is currently taking place
• Constructor for CSMobile needs a City
– we need to pass an instance of the City class to the
constructor for CSMobile
– where can we find an instance of City?
– since we’re in the City class constructor (i.e.,
execution is taking place inside the City class), we
can use this as our instance of City
Actual parameter sent by city
S
_csMobile = new CSMobile(this);
City
R
public CSMobile( City myCity )
Parameters
Formal parameter used by
CSMobile constructor
21 of 32
© 2006 Pearson
Education
Methods with Multiple Parameters
• Declaring a method that accepts more than
one parameter is quite simple
– for example, let’s say that the CSMobile is about to
get a speeding ticket!
– an instance of the Policeman class needs to know
about the CSMobile as well as the City in order to
write up the ticket
– choice of “hardwiring” particular City in Policeman
constructor or allowing City to be totally dynamic in
a method like this:
public void giveTicket(City myCity,
CSMobile car) {
}
Formal parameters
method would be called like this:
_policeman.giveTicket(_city, _csMobile);
instance of class
Policeman
Parameters
instance of
class City
22 of 32
instance of
class
CSMobile
© 2006 Pearson
Education
Method Overloading
• What if we usually want to repaint the
CSMobile red?
– assume the CSMobile starts as white
– don’t want to have to specify a red color each time
– but still want to have the capability to paint it a color
other than red
• Method overloading lets you make multiple
versions of the same method with different
parameters
– method name is the same, but parameter lists are
different so the methods’ signatures are different
– parameters must be different in type, not just in name
– allows further customization of methods
• Let’s see it!
Parameters
23 of 32
© 2006 Pearson
Education
CSMobile with Method Overloading
/**
* This class demonstrates method
* overloading in the CSMobile.
*/
public class CSMobile {
private java.awt.Color _color;
public CSMobile() {
_color = java.awt.Color.white; // default
}
public void setColor(java.awt.Color newColor){
_color = newColor;
}
public void setColor() {
this.setColor( java.awt.Color.red );
}
}
Parameters
24 of 32
© 2006 Pearson
Education
Method Overloading Syntax Explained
• Note: Two methods with the same name, but
different lists of parameters
public void setColor( java.awt.Color newColor )
(1 parameter)
public void setColor()
(0 parameters)
• Example of a method that calls another:
public void setColor() {
this.setColor( java.awt.Color.red );
}
– often when you overload, you call a different version
of the method with different parameters
– in this case, adding the default value
– advantages:
• less code (except in trivial situations like this one)
• less room for error —much easier to find and fix errors
in one method that other methods depend on than to
fix the same error in many methods
– advantages over procedural programming:
• no ugly case/switch statements (we’ll cover them
later)
• avoids unpredictability of default parameters
Parameters
25 of 32
© 2006 Pearson
Education
Return Types
• Let’s say we want to ask the CSMobile for its
color
• Just like methods can take in information, they
can also give back information (remember the
example of a function that computes a result)
• Methods can send a response back to the
object that called the method
Sending
Object
message
Receiving
Object
Method
optional return
• First, method must specify what type of object
it responds with
– type takes the place of void in the method
declaration
• Then, at end of method it returns an object of
the declared type to the calling method
• How does this look?
Parameters
26 of 32
© 2006 Pearson
Education
Return Types
/**
* This class demonstrates the
* CSMobile using return types.
*/
public class CSMobile {
private java.awt.Color _color;
public CSMobile() {
_color = java.awt.Color.white;
}
// setColor methods elided
public java.awt.Color getColor() {
return _color;
}
}
Parameters
27 of 32
© 2006 Pearson
Education
Return Types Syntax Explained
public java.awt.Color getColor()
– note that instead of void, method says
java.awt.Color
– the void keyword means the method returns nothing
– void can be replaced with a class type
• any object of appropriate type can be returned
• something that calls the getColor method will expect
a java.awt.Color to be returned to it
example:
_carcolor = _csMobile.getColor();
instance variable
of type Color
instance variable
of type CSMobile
return _color;
– at the end of a method, use the return keyword to
give back an object of the appropriate class type
– _color is a java.awt.Color so it can be returned
by the getColor method
Parameters
28 of 32
© 2006 Pearson
Education
Accessors and Mutators (1 of 3)
• Accessor and Mutator methods are simple
helper methods for getting or setting one
property of an object
• These methods are very simple but illustrate
the concepts of parameters and return types
• Mutator Methods:
– “set” methods
– use parameters but generally not a return type (return
void)
– exist primarily to change the value of a particular
private instance variable (property) in a safe way
• as we will learn in later lectures, it allows a
programmer to prevent variables from being set to bad
(error) values, like null
– names usually start with set (setColor, setSize,
setCity)
– Examples, respectively:
• method to set the color of an object
• method to set the size of an object
• method to set the city that a CSMobile drives in
Parameters
29 of 32
© 2006 Pearson
Education
Accessors and Mutators (2 of 3)
• Accessor Methods:
– “get” methods
– use return types but generally not parameters
(parentheses after the method name are empty)
– exist primarily to return information to the calling
method
– names usually start with get (getColor, getSize,
getCity)
– Examples, respectively:
• method that returns the color of an object
• method that returns the size of an object
• method that returns the city that a CSMobile drives
in
• Accessors and mutators usually occur in pairs
public void setColor(java.awt.Color newColor)
method of CSMobile was really just a mutator
public java.awt.Color getColor()
method of CSMobile was really just an accessor
Parameters
30 of 32
© 2006 Pearson
Education
Accessors and Mutators (3 of 3)
• What we recommend you should do:
– use helper (accessor and mutator) methods to give a class
safe access to other class’ instance variables (if necessary)
• What we recommend you never do (although it is legal Java
syntax):
public class CSMobile {
//a public instance variable!!
public java.awt.Color _color;
public CSMobile() {
_color = java.awt.Color.white;
}
}
public class City {
private CSMobile _car;
public City() {
_car = new CSMobile();
//accessing a public instance variable
_car._color = java.awt.Color.red;
}
}
• This allows another class to change the value of _color without the
CSMobile knowing. This means the CSMobile cannot check for bad
colors (like puke green) and will not know that it should go get the
new paint job!
USE ACCESSORS AND MUTATORS, NOT
PUBLIC INSTANCE VARIABLES!!!
Parameters
31 of 32
© 2006 Pearson
Education
Parameters
32 of 32
© 2006 Pearson
Education