1 / 37

PARAMETERS

PARAMETERS. Making Messages Specific Setting Up Associations Actual and Formal Parameters Return Types Accessor and Mutator Methods Local Variables Garbage Collection. Parameters. 1 of 37. September 17, 2013. Problem 1: Making Messages Specific. CS15Mobile needs a paint job!

gad
Download Presentation

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 • Local Variables • Garbage Collection Parameters 1 of 37 September 17, 2013

  2. Problem 1: Making Messages Specific • CS15Mobile needs a paint job! • Let’s say we want to give CS15Mobile the capability of being painted different colors • One solution: • add a method to CS15Mobile 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 onesetColor method in class CS15Mobile in which we could specify the color that we want to paint with • How do we make a message specific? Parameters 2 of 37

  3. Problem 2: A Smart CS15Mobile • CS15Mobile is going for a drive! • It’s time to associate CS15Mobile with the City it’s driving in • this way it can call methods on class City to ask where schools and parks are located • Remember, CitycontainsCS15Mobile • Cityhas an instance variable of class CS15Mobile • this meansCity can call methods on this instance • But containment relationship is not symmetric • CS15Mobilecan’t automatically call methods on City (it doesn’t know about the city) • So how can we enable CS15Mobile to know its container, City, so it can call methods on City? • Need to associate a City instance with a CS15Mobile instance in order for a CS15Mobile to call methods on City • How do we associate two objects? Parameters 3 of 37

  4. Parameters • Answer: Parameters! • We use Parameters in two 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 CS15Mobile know about the City it is driving in • this is the way to set up association (“knows-about”) relationships • But how? Parameters 4 of 37

  5. Sending and Receiving • The 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 • a mathematician can “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 5 of 37

  6. Formal and Actual Parameters • x is a formal parameter • formal parameters are “dummy” variables that represent the type of object that will be passed in when the method is called; call them what you like! • they have no value of their own; they 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 • sender passes a specific value/instance with method call to receiver f(x) = x2 + 2x + 5 • Let’s see a method that receives parameters! f(x) = x2 + 2x + 5 2 13 actual parameter formal parameter returns Parameters 6 of 37

  7. Syntax: The Receiver package Demos.Car; /** * This class models a CS15Mobile that * can be repainted any color. The instance * variables and other methods that we defined * in previous lectures are elided for brevity. */ public class CS15Mobile { private java.awt.Color _color; // other instance variable declarations elided public CS15Mobile() { _color = java.awt.Color.WHITE; // default // other instance variable definitions elided } public void setColor(java.awt.ColornewColor) { _color = newColor; } public void repaintCar() { // assume these methods declared below repaintCar this.sandCar(); this.removeDings(); this.paintWithColor(_color); this.polish(); } // other methods elided } type name formal parameter Parameters 7 of 37

  8. Syntax: The Sender package Demos.Car; /** * This simple App only sends the CS15Mobile’s * setColor method a parameter, then repaints * the car. */ public class SimpleApp extends javax.swing.JFrame { private CS15Mobile _15mobile; public SimpleApp() { _15mobile = new CS15Mobile(); _15mobile.setColor(java.awt.Color.BLUE); _15mobile.repaintCar(); } public static void main (String[] argv) { new SimpleApp(); } } actual parameter (no type needed) What color will the car be repainted? Parameters 8 of 37

  9. Syntax for the Receiver Explained (1/2) • Syntax for class CS15Mobile: private java.awt.Color _color; • java.awt.Color is the built-in Java class that represents a color • CS15Mobile has an instance variable representing its color that is 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) • it’s okay for them to be public instance variables as a special case because they are constant (cannot be changed!) so we don’t need to worry about their value changing unexpectedly • more on how you can create constants later in the course Parameters 9 of 37

  10. Syntax for the Receiver Explained (2/2) type name public void setColor(java.awt.ColornewColor) { • this method receivesa parameter (and returns none) • 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 • java.awt.ColornewColoris a formal parameter • newColoris the name that the parameter will be referred to as, only in this method • can only use newColor within body of setColor(…) method (i.e., within the curly braces “{} ”) • don’t have to name it newColor, can use any name! • a method that receives one parameter is always declared with the form: methodName(param-typeparam-name) • since formal parameter is only accessible within method, copy it into an instance variable so it is accessible to all methods within the class and doesn't disappear when method ends _color = newColor; read: _color “gets” the same Color as newColor(i.e., whatever actual value newColor is set to when setColor(…) is called) formalparameter Parameters 10 of 37

  11. Syntax for the Sender Explained • Syntax for class SimpleApp: _15mobile.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, don’t need java.awt.Colorin addition to the actual parameter) • this is because the parameter type is already specified in the CS15Mobile’ssetColor(…) method • what if you tried to pass in something that wasn’t a Color? _15mobile.setColor(randomInstance); • you would get a compiler error like: Incompatible type for method setColor() Can’t convert randomInstance to Color. actual parameter (value) Parameters 11 of 37

  12. More on Actual and Formal Parameters • One-to-one correspondence needed between formal and actual parameters • order, type (class) of instances, and number of parameters sentmust match order, type, and number declared in method! _15mobile.setColor(java.awt.Color.BLUE) • sends one parameter of type java.awt.Color • which matches: public void setColor(java.awt.ColornewColor) • expects one parameter of type java.awt.Color • Note: java.awt.Color.BLUE is very different from java.awt.Color blue. The former indicates a constant (with a specific value) and the latter would declare a variable of typejava.awt.Colornamedblue (without value). • 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 • receiver uses a dummy name to represent the parameter • sender may send different actual parameters • may send java.awt.Color.BLUE, java.awt.Color.Yellow, etc. tosetColor(…) method Parameters 12 of 37

  13. Signatures A method’s signature is composed of its… • identifier (name) • class of its parameters • order of its parameters • Like a person’s signature, a method’s signature must be unique. • Creating two methods in one class with the exact same signature will cause an error like: someMethod() is already defined in MyClass: public void someMethod(){ • Methods in different classes can still have the same signature; Java disambiguates based on type of instance Parameters 13 of 37

  14. References as Values of Variables • To send messages to an object, we must have a name for it • in Java, we can only access objects via references to them • Objects only contain references to component objects _color java.awt.Color • The equals sign =actually assigns references _15mobile = new CS15Mobile(); • makes _15mobile refer to a new instance of class CS15Mobile • i.e., _15mobile is assigneda reference to an instance created byCS15Mobile() _color = newColor; //not new Color!!! • makes _color refer to the same instance of Color class that newColor does • i.e., _color is assigned the same color as newColor • both now refer to the same color instance refers to an instance of Parameters 14 of 37

  15. Review: References Revealed • A reference is just a pointer to a location in memory • a version of an address people can understand • it’s easier to keep track of a name than some weird thing (like 0xeff8a9f4) • holds a memory address where instance is stored • Java also has primitives, which are not objects and do not have pointers (more on this later) What’s a reference again? You knownothing,Jon Snow. reference to instance 1 reference to instance 2 reference to instance 3 Parameters 15 of 37

  16. Parameters as References • Formal parameters refer to the same instance while the method is active; when the method is finished, so is the formal parameter name, which is why we usually store the parameter in an instance variable • the sender sends a reference to an instance using an actual parameter • the receiver’s corresponding formal parameter then refers to the same instance SENDER public class SimpleApp { ... _15mobile.setColor(java.awt.Color.BLUE); ... } Actual parameter java.awt.Color.BLUE RECE I VER public class CS15Mobile { ... public void setColor(java.awt.ColornewColor){ ... } } Formal parameter Parameters 16 of 37

  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 CS15Mobile to know about its City -- called association • CS15Mobile 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 37

  18. Syntax: The Receiver package Demos.Car; /** * This class models a CS15Mobile that knows about * its City. Again, the instance variables, * constructor, and other methods that we defined * in earlier slides are elided. */ public class CS15Mobile { private City _city; public CS15Mobile(City myCity) { _city = myCity; // store association // More code elided } // … Other methods of CS15Mobile elided } // End of class CS15Mobile So when an instance of City instantiates aCS15Mobileit is expected to pass a reference to itself to theCS15Mobile’s constructor, so that the CS15Mobilecan be associated with the instance City. The instance ofCitywill be referenced by the formal parameter namemyCity, whose value is then stored in the instance variable_city. Now the CS15Mobile can call any ofCity's public methods on  _city. Parameters 18 of 37

  19. Syntax: The Sender package Demos.Car; /** * This class models a city where CS15Mobiles * exist. Because the City contains the * CS15Mobile, it can send the CS15Mobile the * reference to an instance of itself. */ public class City { private CS15Mobile _15mobile; public City() { _15mobile = new CS15Mobile(this); } // … Other methods of City elided } // End of class City • Remember this(“Making Objects” lecture, slide 24)? • shorthand for “this instance”, i.e., instance where execution is currently taking place • To associate itself with CS15Mobile, Citypasses theCS15Mobilea reference to itself by using the reserved wordthis. • Now_15mobile is associated with “this” instance ofCity . Parameters 19 of 37

  20. Syntax for the Receiver Explained • Syntax for class CS15Mobile public class CS15Mobile { private City _city; // _city is a variable storing the // City that this CS15Mobile is driving in // CS15Mobile constructor public CS15Mobile(City myCity) { _city = myCity; } } • standard constructor that receives a parameter • assigns the parameter passed in, myCity, to the instance variable _city • CS15Mobile now knows aboutmyCity Parameters 20 of 37

  21. Syntax for the Sender Explained • Inside constructor for class City _15mobile = new CS15Mobile(this); • Constructor for CS15Mobile needs a City • we need to pass an instance of the City class to the constructor for CS15Mobile inside constructor for class City • where can we find an instance of City? • which instance of City? • since we’re in the Cityclass' constructor (i.e., execution is taking place inside a Cityinstance), use thisas our instance of City Actual parameter sent by a City instance SENDER _15mobile = new CS15Mobile(this); Boston RECE I VER public CS15Mobile(City myCity) Formal parameter used by CS15Mobile constructor Parameters 21 of 37

  22. Methods with Multiple Parameters • Declaring a method that accepts more than one parameter is quite simple • for example, let’s say that the CS15Mobile is about to get a speeding ticket! • an instance of the Policeman class needs to know about the CS15Mobileas well as the City in order to write up the ticket • we could “hardwire” a particularCity in Policeman’s constructor (meaning the policeman will always be associated with that city) or allow City to be totally dynamic in a method like this: public void giveTicket(City myCity, CS15Mobile car) { } This way Policeman can give a ticket to any CS15Mobile in any City method would be called like this: _policeman.giveTicket(_providence,_andysVolvo); Formal parameters instance of class CS15Mobile instance of class Policeman instance of class City Parameters 22 of 37

  23. message Sending Object Receiving Object Method optional return Return Types • Let’s say we want to ask the CS15Mobile 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 • so far, we’ve seen the word void in method declarations – the type of object that a method responds with takes the place of void • At the end of the called method, an object of the specified return type is returned to the caller • How does this look? Parameters 23 of 37

  24. Return Types package Demos.Car; /** * This class demonstrates the * CS15Mobile using return types. */ public class CS15Mobile { private java.awt.Color _color; // other instance variables elided public CS15Mobile(City myCity) { _color = java.awt.Color.WHITE; // city association code elided } // setColor method elided public java.awt.ColorgetColor() { return _color; } } Parameters 24 of 37

  25. Return Types Syntax Explained public java.awt.ColorgetColor() • note that instead of void, method says java.awt.Color • the void keyword means the method returns nothing • void can be replaced with class type to be returned • any object of the declared type can be returned • something that calls the getColormethod will expect a java.awt.Color to be returned example: _carColor = _15mobile.getColor(); • at the end of a method, use the return keyword to give back an object of the appropriate class type • In the above example, the value returned by _15mobile.getColor() is assigned to the instance variable _carColor instance of type java.awt.Color instance variable of type java.awt.Color instance variable of type CS15Mobile Parameters 25 of 37

  26. Accessors and Mutators (1 of 2) • Accessor and Mutator methods are simple helper methods used to “get” or “set” some 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 do not return anything (return void) • exist primarily to change the value of a particular private instance variable (property) in a safe way • allows programmer to give variables specific values, instead of leaving them 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 CS15Mobiledrives in Parameters 26 of 37

  27. Accessors and Mutators (2 of 2) • Accessor Methods: • “get” methods • use return types but generally do not take parameters • 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 CS15Mobile drives in • Accessors and Mutators often occur in pairs //setColor(…) in CS15Mobile is a mutator! public void setColor(java.awt.ColornewColor){ _color = newColor; } //getColor() in CS15Mobile is an accessor! public java.awt.ColorgetColor(){ return _color; } Parameters 27 of 37

  28. What if you want to geta property from one instance and use it to seta property of another instance? For example, you want to get the current color from one instance of class CS15Mobile and use it to set the current color of another instance of class CS15Mobile How can you do this? Answer: use a local variable! Using Accessors and Mutators Together What’s a local variable? And why do I need it?!? Parameters 28 of 37

  29. Local Variables We’ve seen instance variables they operate within the scope of the entire class an instance variable that belongs to a class can be accessed anywhere in the class — within any method they cannot be directly accessed by other classes (because they shouldn’t be public !) A local variable is declared within a single method the local variable’s scope is only that method this means that the local variable can be used only within the method in which it was created The scope of a variable determines where it can be used instance variables can be used by all methods of a class local variables can only be used within the method that creates them syntactically, scope of any variable is the code between the curly braces of where it is declared Let’s see an example... Parameters 29 of 37

  30. Example to help you with LiteBrite /** * Example written to demonstrate the use of * local variables in conjunction with accessor * and mutator methods. */ public class ContrivedExample { private CS15Mobile _15MobileOne, _15MobileTwo; public ContrivedExample() { _15MobileOne = new CS15Mobile(); _15MobileTwo = new CS15Mobile(); _15MobileOne.setColor(java.awt.Color.BLUE); this.contrivedMethod(); // _15MobileOne has a blue color } public void contrivedMethod() { java.awt.ColortempColor = _15MobileOne.getColor(); // accessor // tempColor: blue _15MobileTwo.setColor(tempColor); // mutator //_15MobileTwo now also has a blue color } } Parameters 30 of 37

  31. Syntax forcontrivedMethod Explained java.awt.ColortempColor = _15MobileOne.getColor(); tempColor is a local variable stores the return value of _15MobileOne.getColor() no need for modifier (i.e.,private) becausetempColorcan only be used withincontrivedMethod OncecontrivedMethodhas finished execution, the value oftempColorwill “go out of scope” — will no longer exist you will not be able to do anything with thatjava.awt.Colorexcept incontrivedMethod note: by CS15 convention, local variables do not begin with an underscore You can also usenewto create local variables, for example: CS15Mobile mobile = new CS15Mobile(); It is unnecessary to store data as an instance variable if only one method needs to use it local variables are used to store data temporarily example: storing intermediate data in calculations _15MobileTwo.setColor(tempColor); Pass tempColor as a parameter to setColor just like you’d pass an instance variable! Could have alternatively written: we refer to this technique as nesting one method call inside another avoids storing the color in a local variable altogether _15MobileTwo.setColor(_15MobileOne.getColor()); Parameters 31 of 37

  32. Methods and Variable Types There are three kinds of variables a method can use: local variables (created and known only within that method) parameters (acting like local variables) instance variables (known to all methods in the class) When do we use which kind of variable? depends on how we want to deal with the variable outside of the method different kinds of variables have different levels of accessibility or scope parameters and local variables exist only within the method parameters are passed between methods instance variables exist within the class and are accessible to all methods of the class Class 1 Instance Variables Class 2 Instance Variables Method A Local Variables Method B Local Variables Method C Local Variables Method D Local Variables Parameters/returns Parameters 32 of 37

  33. Lost References / Garbage Collection What happens when a variable goes out of scope? you can no longer use the variable’s name to access the instance it refers to you lose a reference to that instance How else can you lose a reference to an instance? assign variable to null (no useful value) assign variable to some other instance What happens when there is no reference to an instance? the instance is garbage collected — it is removed from memory by the Java Virtual Machine to put it simply, the instance doesn’t exist anymore So make sure you don’t lose all references to an instance -- otherwise you won’t be able to access it anymore and the instance will disappear! Parameters 33 of 37

  34. Garbage Collection Example package GameOfThrones; /** * Example written to demonstrate garbage * collection in Java. */ public class FirstSeason{ private Character _character; public FirstSeason () {//constructor code elided } public void makeStark() { _character = new Character(“Ned”); } public void makeLannister() { _character = new Character(“Joffrey”); } } Parameters 34 of 37

  35. Garbage Collection When the method makeStark() is called When the method makeLannister()is called next The old instance of Character in _charactergets erased (goodbye Ned, hello Joffrey!) Garabage Collection works the same way when local variables go out of scope! _character Parameters 35 of 37

  36. Parameters Review Parameter passing checklist: does the number of actual parameters equal the number of formal parameters? does the type (class) of each actual parameter match the type of its corresponding formal parameter? are the parameters passed in correct order? are parameter types specified in method declaration but omitted from method call? Multiple mechanisms for factoring information: classes factor out common properties and methods of instances methods use parameters to factor out values of a piece of data Next, we’ll find out about another form of factoring: Inheritance Parameters 36 of 37 September 17, 2013

  37. Announcements • Reminder: Clock due tomorrow at 11:59pm. • No late handin! • LiteBrite goes out today! DQ’s will be due on Saturday at 10pm. Help Session will be Sunday at 5:30pm in MacMillan 117 • No late handins for DQs! • DQs must be handed in electronically. With the “cs015_handin <Project Name>” command from the terminal. • Only after doing this you will receive a confirmation email. • Complete lab 0 (Intro to Linux) and turn in your signed collaboration policy if you haven’t already! • Complete Lab 1 (Intro to Java) this week. • Remember to print out your code when going to hours. You can do this by running “cs015_print *.java” from inside the directory that has your code • Concept of the week coming up this week and several announcements so check the website! Parameters

More Related