1 / 32

PARAMETERS

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

imani-short
Télécharger la présentation

PARAMETERS

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


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

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

  3. 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 • Citycan automatically call methods on CSMobile • But containment relationship is not symmetric • CSMobilecan’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

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

  5. 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() receiving method specifics green f(x) = x2 + 2x + 5 2 specific value receiving function Parameters

  6. 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 f(x) = x2 + 2x + 5 • Let’s see a method that receives parameters! 2 13 actual parameter formal parameter returns Parameters

  7. 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 } // other methods elided } formal parameter Parameters

  8. 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 ); } public static void main ( String[] argv ) { SimpleApp app = new SimpleApp(); } } actual parameter Parameters

  9. 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.whiteis a constant • java.awt.Color class has many predefined constantcolors 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

  10. More Syntax for the Receiver public void setColor( java.awt.Color newColor ) { • example of a method that receivesa parameter • parameter is of typejava.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-typeparam-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) type that method expects formal parameter (name) Parameters

  11. 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) Parameters

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

  13. Signatures • The combination of the method identifier,the class of its parameters,and the order of its parametersis 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

  14. 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 instance of class CSMobile • i.e., _csMobile is assigneda reference to an instance created byCSMobile() _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 Parameters

  15. 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 reference to instance 2 reference to instance 3 Parameters

  16. 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!) public class SimpleApp { ... _csMobile.setColor(java.awt.Color.blue); ... } public class CSMobile { ... public void setColor(java.awt.Color newColor) { ... } } SENDER Actual parameter java.awt.Color RECE I VER Formal parameter Parameters

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

  18. 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 CSMobilecan call methods on the City . Parameters

  19. 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 _csMobileis associated with “this” instance of City . Parameters

  20. 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 aboutmyCity Parameters

  21. 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 S City R Formal parameter used by CSMobile constructor Parameters

  22. 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 CSMobileas well as the City in order to write up the ticket • choice of “hardwiring” particularCity 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 Parameters

  23. Method Overloading • What if we usually want to repaint the CSMobilered? • 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

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

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

  26. message Sending Object Receiving Object Method optional return 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? Parameters

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

  28. 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 getColormethod 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 CSMobile instance variable of type Color Parameters

  29. 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 CSMobiledrives in Parameters

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

  31. 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!! publicjava.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

  32. Parameters

More Related