32
PARAMETERS • Making Messages Specific • Setting Up Associations • Actual and Formal Parameters • Return Types • Accessor and Mutator Methods

PARAMETERS Making Messages Specific Setting Up Associations Actual and Formal Parameters Return Types Accessor and Mutator Methods

Embed Size (px)

Citation preview

Page 1: PARAMETERS Making Messages Specific Setting Up Associations Actual and Formal Parameters Return Types Accessor and Mutator Methods

PARAMETERS

• Making Messages Specific

• Setting Up Associations

• Actual and Formal Parameters

• Return Types

• Accessor and Mutator Methods

Page 2: PARAMETERS Making Messages Specific Setting Up Associations Actual and Formal Parameters Return Types Accessor and Mutator Methods

© 2006 Pearson Education

Parameters 2 of 32

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?

Page 3: PARAMETERS Making Messages Specific Setting Up Associations Actual and Formal Parameters Return Types Accessor and Mutator Methods

© 2006 Pearson Education

Parameters 3 of 32

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?

Page 4: PARAMETERS Making Messages Specific Setting Up Associations Actual and Formal Parameters Return Types Accessor and Mutator Methods

© 2006 Pearson Education

Parameters 4 of 32

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?

Page 5: PARAMETERS Making Messages Specific Setting Up Associations Actual and Formal Parameters Return Types Accessor and Mutator Methods

© 2006 Pearson Education

Parameters 5 of 32

Sending and Receiving

• A sending method sends specifics of a given situation to a receiving 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:

setColor()green

f(x) = x2 + 2x + 52

specificsreceiving

method

specific value receiving function

Page 6: PARAMETERS Making Messages Specific Setting Up Associations Actual and Formal Parameters Return Types Accessor and Mutator Methods

© 2006 Pearson Education

Parameters 6 of 32

•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

f(x) = x2 + 2x + 5

• Let’s see a method that receives parameters!

Formal and Actual Parameters

2 13

actual parameter formal parameter returns

Page 7: PARAMETERS Making Messages Specific Setting Up Associations Actual and Formal Parameters Return Types Accessor and Mutator Methods

© 2006 Pearson Education

Parameters 7 of 32

/** * 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 }

// other methods elided}

Syntax: The Receiver

formal parameter

Page 8: PARAMETERS Making Messages Specific Setting Up Associations Actual and Formal Parameters Return Types Accessor and Mutator Methods

© 2006 Pearson Education

Parameters 8 of 32

/** * 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 );

}

public static void main ( String[] argv ) { SimpleApp app = new SimpleApp(); }}

Syntax: The Sender

actual parameter

Page 9: PARAMETERS Making Messages Specific Setting Up Associations Actual and Formal Parameters Return Types Accessor and Mutator Methods

© 2006 Pearson Education

Parameters 9 of 32

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

Page 10: PARAMETERS Making Messages Specific Setting Up Associations Actual and Formal Parameters Return Types Accessor and Mutator Methods

© 2006 Pearson Education

Parameters 10 of 32

More Syntax for the Receiver

public void setColor( java.awt.Color newColor ) {

– 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 Coloras newColor (i.e., whatever value newColor was set to by sender)

type that method expects formal parameter (name)

Page 11: PARAMETERS Making Messages Specific Setting Up Associations Actual and Formal Parameters Return Types Accessor and Mutator Methods

© 2006 Pearson Education

Parameters 11 of 32

Syntax for the Sender

• Syntax for class SimpleApp:

_csMobile.setColor( java.awt.Color.blue );

– 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.

actual parameter (value)

Page 12: PARAMETERS Making Messages Specific Setting Up Associations Actual and Formal Parameters Return Types Accessor and Mutator Methods

© 2006 Pearson Education

Parameters 12 of 32

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

Page 13: PARAMETERS Making Messages Specific Setting Up Associations Actual and Formal Parameters Return Types Accessor and Mutator Methods

© 2006 Pearson Education

Parameters 13 of 32

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();

Page 14: PARAMETERS Making Messages Specific Setting Up Associations Actual and Formal Parameters Return Types Accessor and Mutator Methods

© 2006 Pearson Education

Parameters 14 of 32

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 java.awt.Color

• The equals operator actually assigns references

_csMobile = new CSMobile();

makes _csMobile refer to a new instanceof 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

refers to an instance of

Page 15: PARAMETERS Making Messages Specific Setting Up Associations Actual and Formal Parameters Return Types Accessor and Mutator Methods

© 2006 Pearson Education

Parameters 15 of 32

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 toinstance 1

reference toinstance 2

reference to instance 3

Page 16: PARAMETERS Making Messages Specific Setting Up Associations Actual and Formal Parameters Return Types Accessor and Mutator Methods

© 2006 Pearson Education

Parameters 16 of 32

• 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!)

public class SimpleApp { ...

_csMobile.setColor(java.awt.Color.blue);

...

}

public class CSMobile {

... public void setColor(java.awt.Color newColor) {

...

}

}

java.awt.Color

Parameters as References

Actual parameter

Formal parameter

SENDER

RECE I VER

Page 17: PARAMETERS Making Messages Specific Setting Up Associations Actual and Formal Parameters Return Types Accessor and Mutator Methods

© 2006 Pearson Education

Parameters 17 of 32

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...

Page 18: PARAMETERS Making Messages Specific Setting Up Associations Actual and Formal Parameters Return Types Accessor and Mutator Methods

© 2006 Pearson Education

Parameters 18 of 32

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 .

Page 19: PARAMETERS Making Messages Specific Setting Up Associations Actual and Formal Parameters Return Types Accessor and Mutator Methods

© 2006 Pearson Education

Parameters 19 of 32

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 .

Page 20: PARAMETERS Making Messages Specific Setting Up Associations Actual and Formal Parameters Return Types Accessor and Mutator Methods

© 2006 Pearson Education

Parameters 20 of 32

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

Page 21: PARAMETERS Making Messages Specific Setting Up Associations Actual and Formal Parameters Return Types Accessor and Mutator Methods

© 2006 Pearson Education

Parameters 21 of 32

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

_csMobile = new CSMobile(this);

public CSMobile( City myCity )

Actual parameter sent by city

Formal parameter used by CSMobile constructor

S

R

City

Page 22: PARAMETERS Making Messages Specific Setting Up Associations Actual and Formal Parameters Return Types Accessor and Mutator Methods

© 2006 Pearson Education

Parameters 22 of 32

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) {}

method would be called like this:

_policeman.giveTicket(_city, _csMobile);

Formal parameters

instance of class Policeman

instance of class City

instance of class CSMobile

Page 23: PARAMETERS Making Messages Specific Setting Up Associations Actual and Formal Parameters Return Types Accessor and Mutator Methods

© 2006 Pearson Education

Parameters 23 of 32

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!

Page 24: PARAMETERS Making Messages Specific Setting Up Associations Actual and Formal Parameters Return Types Accessor and Mutator Methods

© 2006 Pearson Education

Parameters 24 of 32

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 );

}

}

Page 25: PARAMETERS Making Messages Specific Setting Up Associations Actual and Formal Parameters Return Types Accessor and Mutator Methods

© 2006 Pearson Education

Parameters 25 of 32

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

Page 26: PARAMETERS Making Messages Specific Setting Up Associations Actual and Formal Parameters Return Types Accessor and Mutator Methods

© 2006 Pearson Education

Parameters 26 of 32

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

• 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?

Sending Object

Receiving Object

Method

message

optional return

Page 27: PARAMETERS Making Messages Specific Setting Up Associations Actual and Formal Parameters Return Types Accessor and Mutator Methods

© 2006 Pearson Education

Parameters 27 of 32

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;

}

}

Page 28: PARAMETERS Making Messages Specific Setting Up Associations Actual and Formal Parameters Return Types Accessor and Mutator Methods

© 2006 Pearson Education

Parameters 28 of 32

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();

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

instance variable of type Color

instance variable of type CSMobile

Page 29: PARAMETERS Making Messages Specific Setting Up Associations Actual and Formal Parameters Return Types Accessor and Mutator Methods

© 2006 Pearson Education

Parameters 29 of 32

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

Page 30: PARAMETERS Making Messages Specific Setting Up Associations Actual and Formal Parameters Return Types Accessor and Mutator Methods

© 2006 Pearson Education

Parameters 30 of 32

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

Page 31: PARAMETERS Making Messages Specific Setting Up Associations Actual and Formal Parameters Return Types Accessor and Mutator Methods

© 2006 Pearson Education

Parameters 31 of 32

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!!!

Page 32: PARAMETERS Making Messages Specific Setting Up Associations Actual and Formal Parameters Return Types Accessor and Mutator Methods

© 2006 Pearson Education

Parameters 32 of 32