Lecture 11 - Kennesaw State University

Lecture 11 - Kennesaw State University

Lecture 11 Parameters, Overloading Methods, and Random Garbage CSE 1322 4/26/2018 11-1 What is a Method? Think of a method as a black box that contains the detailed implementation for a specific task. The method may use inputs (parameters) and may return an output with a specific type. Optional arguments for Input Optional return value Method Header Method body 01/25/2020

Black Box 2 Method Structure Modifiers Method Header Method Body 01/25/2020 Return Type Method Name Formal Parameters public static int addTwoNums (int x, int y)

{ return x + y; } 3 Calling the Method Modifiers Method Header Method Body Return Type Method Name Formal Parameters public static int addTwoNums (int x, int y)

{ return x + y; } Actual parameters (called arguments) int result = addTwoNums (5, 2); 01/25/2020 4 Parameters There are three main types of parameters: 1. Value - passes a copy of the value of the variable to the method. This is the default. 2. Reference (C#)- passes a reference to the actual variable. Keyword is ref. Use this when you want to pass a value in and have any change to that value be persistent when the method is complete 3. Out (C#) - passes a reference to the actual variable. Keyword is out. Use this when you want the method to initialize a value and place it for later use in the actual variable (persists when the method is complete) 4. Note that Java passes all parameters by value. 5. C++ uses both Call-by-reference and Call-by-value 4/26/2018

11-5 Example 1 - and the output is ? static void B (int x) x += 9; PRINT (x); } { // Built-in type argument passing public static void M/main (S/string[] args) { int a = 42; PRINT (a); // Prints 42 B (a); // Prints 51 because is call-by-value; PRINT (a); // Prints 42 } 4/26/2018

11-6 Example 2 - and the output is ? static void B (ref int x) { x += 9; Console.WriteLine (x); } public static void Main (string[] args) { int a = 42; Console.WriteLine (a); // Prints 42 B (ref a); // Prints 51 BUT! Console.WriteLine (a); // Prints 51 } 4/26/2018 a has changed! 11-7 What about out? Remember, this is used to initialize a variable Why even have it? We have ref, right?

Honestly, out isnt used often, but: Marks the intent of what youre doing Could prevent bad data from coming in 4/26/2018 11-8 Example 3 - and the output is ? static void B (out int x) { x = 9; Console.WriteLine (x); } public static void Main (string[] args) { int a; // We can't print this yet - not initialized B (out a); // Initializes a and prints 9 Console.WriteLine (a); // Prints 9 } 4/26/2018 11-9

What about Complex Data Types? With classes/objects, we still pass by value HOWEVER, we are copying the reference Well start with code, then look at whats going on 4/26/2018 11-10 class Dog { public int weight; } static void B(Dog x) { // IMPORTANT! x is referencing the same // chunk of memory myDog is referencing! x.weight += 9; PRINT(x.weight); } public static void M/main(S/string[] args) Dog myDog = new Dog(); myDog.weight = 10; PRINT(myDog.weight); // 10 B(myDog);

// 19 PRINT(myDog.weight); // 19 } 4/26/2018 { 11-11 class Dog { public int weight; } static void B(Dog x) { x.weight += 9; PRINT(x.weight); } public static void M/main(S/string[] args) Dog myDog = new Dog();

{ myDog myDog.weight = 10; PRINT(myDog.weight); B(myDog); weight = 0; PRINT(myDog.weight); } 4/26/2018 11-12 class Dog { public int weight; }

static void B(Dog x) { x.weight += 9; PRINT(x.weight); } public static void M/main(S/string[] args) Dog myDog = new Dog(); { myDog myDog.weight = 10; PRINT(myDog.weight); B(myDog); weight = 10; PRINT(myDog.weight); } 4/26/2018 11-13 class Dog

{ public int weight; } static void B(Dog x) { x.weight += 9; PRINT(x.weight); } public static void M/main(S/string[] args) Dog myDog = new Dog(); { myDog myDog.weight = 10; PRINT(myDog.weight); B(myDog); weight = 10; PRINT(myDog.weight);

} // PRINTS 10 to the screen 4/26/2018 11-14 class Dog { public int weight; } static void B(Dog x) { x.weight += 9; PRINT(x.weight); } public static void M/main(S/string[] args) Dog myDog = new Dog(); x

{ myDog myDog.weight = 10; PRINT(myDog.weight); B(myDog); weight = 10; PRINT(myDog.weight); } // MAGIC HAPPENS! x is a copy of myDog... // That is, x points to the same thing // myDog points to 4/26/2018 11-15 IMPORTANT Watch what happens to the weight variable

4/26/2018 11-16 class Dog { public int weight; } static void B(Dog x) { x.weight += 9; // Look at weight before PRINT(x.weight); } public static void M/main(S/string[] args) Dog myDog = new Dog(); x

{ myDog myDog.weight = 10; PRINT(myDog.weight); B(myDog); weight = 10; PRINT(myDog.weight); } 4/26/2018 11-17 class Dog { public int weight; }

static void B(Dog x) { x.weight += 9; // Look at weight after! PRINT(x.weight); } public static void M/main(S/string[] args) Dog myDog = new Dog(); x { myDog myDog.weight = 10; PRINT(myDog.weight); B(myDog); weight = 19; PRINT(myDog.weight); }

4/26/2018 11-18 IMPORTANT Now, myDogs weight has now changed! 4/26/2018 11-19 What about adding ref? class Dog { public int weight; } static void B(ref Dog x) { x = new Dog();

x.weight = 9; Console.WriteLine(x.weight); } public static void Main(string[] args) { Dog myDog = new Dog(); myDog.weight = 10; Console.WriteLine(myDog.weight); B(ref myDog); Console.WriteLine(myDog.weight); } 4/26/2018 11-20 What about adding ref? class Dog { public int weight;

} static void B(ref Dog x) { x = new Dog(); x.weight = 9; Console.WriteLine(x.weight); myDog } public static void Main(string[] args) Dog myDog = new Dog(); myDog.weight = 10; { weight = 0; Console.WriteLine(myDog.weight); B(ref myDog); Console.WriteLine(myDog.weight); }

4/26/2018 11-21 What about adding ref? class Dog { public int weight; } static void B(ref Dog x) { x = new Dog(); x.weight = 9; Console.WriteLine(x.weight); myDog } public static void Main(string[] args) Dog myDog = new Dog(); myDog.weight = 10;

{ weight = 10; Console.WriteLine(myDog.weight); B(ref myDog); Console.WriteLine(myDog.weight); } 4/26/2018 11-22 What about adding ref? class Dog { public int weight; } static void B(ref Dog x) {

x = new Dog(); x.weight = 9; Console.WriteLine(x.weight); myDog } public static void Main(string[] args) Dog myDog = new Dog(); myDog.weight = 10; { weight = 10; Console.WriteLine(myDog.weight); B(ref myDog); Console.WriteLine(myDog.weight); } // OUTPUT 10 4/26/2018 11-23

What about adding ref? class Dog { public int weight; } static void B(ref Dog x) { x = new Dog(); x.weight = 9; Console.WriteLine(x.weight); myDog == x } public static void Main(string[] args) Dog myDog = new Dog(); myDog.weight = 10; { weight = 10;

Console.WriteLine(myDog.weight); B(ref myDog); Console.WriteLine(myDog.weight); } 4/26/2018 11-24 What about adding ref? class Dog { public int weight; } static void B(ref Dog x) { weight = 0; x = new Dog();

x.weight = 9; Console.WriteLine(x.weight); myDog == x } public static void Main(string[] args) Dog myDog = new Dog(); myDog.weight = 10; { weight = 10; Console.WriteLine(myDog.weight); B(ref myDog); Console.WriteLine(myDog.weight); } // Uh oh... 4/26/2018 11-25 Our first piece of garbage

No one is pointing to the old dog anymore! Weve created trash Yes, its really called that (or garbage) Yes, we have a garbage collector (GC) The GC picks up unloved objects Theres no way to recover the unloved dog Rule: when no one points to an object, its TRASHED! 4/26/2018 weight = 0; myDog == x weight = 10; 11-26 What about adding ref? class Dog {

public int weight; } static void B(ref Dog x) { weight = 9; x = new Dog(); x.weight = 9; Console.WriteLine(x.weight); myDog == x } public static void Main(string[] args) Dog myDog = new Dog(); myDog.weight = 10; { weight = 10;

Console.WriteLine(myDog.weight); B(ref myDog); Console.WriteLine(myDog.weight); } 4/26/2018 11-27 What about adding ref? class Dog { public int weight; } static void B(ref Dog x) { weight = 9; x = new Dog(); x.weight = 9;

Console.WriteLine(x.weight); myDog == x } public static void Main(string[] args) Dog myDog = new Dog(); myDog.weight = 10; { weight = 10; Console.WriteLine(myDog.weight); B(ref myDog); Console.WriteLine(myDog.weight); } // OUTPUT 9 to the screen 4/26/2018 11-28 What about adding ref? class Dog

{ public int weight; } static void B(ref Dog x) { weight = 9; x = new Dog(); x.weight = 9; Console.WriteLine(x.weight); myDog == x } public static void Main(string[] args) { Dog myDog = new Dog(); myDog.weight = 10;

weight = 10; Console.WriteLine(myDog.weight); B(ref myDog); Console.WriteLine(myDog.weight); } // OUTPUT 9 to the screen AGAIN because myDog has changed 4/26/2018 11-29 Pass-by-value vs. Pass-byreference vs. Pass-by-referencetype Be careful to note the difference between a pass-by-reference parameter and a parameter of a reference type. Use the activation stack to track local variables and how parameters of the above types affect the variables from one stack frame to the next. 4/26/2018 11-30 Overloading Methods

Method overloading: using the same method name for multiple methods Do not confuse with overriding (from inheritance) The signature of each overloaded method must be unique The signature includes the number, type, and order of the parameters The compiler determines which version of the method is being invoked by analyzing the parameters The return type of the method is not part of the signature 4/26/2018 11-31 Overloading Methods float tryMe (int x) { return x + .375; } float tryMe (int x, float y) { return x*y; } // Which tryMe is called? result = tryMe (25, 4.32f);

4/26/2018 11-32 Overloading Operators In C# and C++, not only can methods be overloaded, even operators (e.g. +, -, *, /, ==, ++, etc) can be overloaded. Java does not allow operator overloading 4/26/2018 11-33 Operator overloading C# enables you to overload most operators to make them sensitive to the context in which they are used. Use operator overloading when it makes an application clearer than accomplishing the same operations with explicit method calls. Example: Class ComplexNumber overloads the plus (+), minus (-) and multiplication (*) operators to enable programs to add, subtract and multiply instances of class ComplexNumber using common mathematical notation

4/26/2018 11-34 Rules for Operator Overloading Keyword operator, followed by an operator symbol, indicates that a method overloads the specified operator. Methods that overload binary operators must take two arguments the first argument is the left operand, and the second argument is the right operand. Overloaded operator methods must be public and static. 4/26/2018 11-35 public class Dog { public string name; public int weight; public Dog(string name, int weight) { this.name = name; this.weight = weight; } public static Dog operator+ (Dog d1, Dog d2) {// Overload the + operator Dog mergedDog = new Dog("ComboDog", 0);

mergedDog.name = d1.name+":"+d2.name; mergedDog.weight = d1.weight+d2.weight; return mergedDog; } } class MainClass { public static void Main(String[] args) { Dog myDog = new Dog("CSE", 8); Dog yourDog = new Dog ("1322", 9); Dog uberDog = myDog + yourDog; // Add two dogs together! Console.WriteLine (uberDog.name + " weighs " + uberDog.weight); } } // OUTPUT is CSE:1322 weighs 17 4/26/2018 11-36

Recently Viewed Presentations

  • Argument Structure in Flux in the History of English

    Argument Structure in Flux in the History of English

    Broader relevance. Argument structure forms the basis of our propositions and, without it, there is no meaning. It is likely that AS is part of our larger cognitive system and not restricted to the language faculty.. For instance, it could...
  • What is a mnemonic device?What is their purpose?What makes ...

    What is a mnemonic device?What is their purpose?What makes ...

    * With your group, create a mnemonic for the continents and oceans. * When you have decided what you will create, you may work together to create a mnemonic device to share with the class. * There are arts &...
  • www.eriding.net

    www.eriding.net

    How Christian upbringing leads to belief: I believe because the sacraments I have received make me feel God loves me. I believe because I meet all my friends at church and Sunday school and we all believe the same.
  • The Japanese Space Gravitational Wave Antenna - DECIGO

    The Japanese Space Gravitational Wave Antenna - DECIGO

    The Japanese Space Gravitational Wave Antenna - DECIGO ... We hope that we will be able to start the R&D for DECIGO soon. The Japanese Space Gravitational Wave Antenna - DECIGO Amaldi6 @Okinawa June 22, 2005 Seiji Kawamura, Takashi Nakamura,...
  • Canapés à l'apéritif ***** La déclinaison des trois foie gras ...

    Canapés à l'apéritif ***** La déclinaison des trois foie gras ...

    Canapés à l'apéritif*****La déclinaison des trois foie grasPressé aux épices doucesPoché au vin chaudMariné au PassitoChutney de figues et caramel de balsamique *****Frégola sarde au ragout de pigeon et morilles ***** Involtini de sole et gambas, espuma au basilic *****...
  • Grambling State University Division of Student Affairs Office ...

    Grambling State University Division of Student Affairs Office ...

    Grambling State University's Peer Mediation Program is an affective form of conflict resolution which allows students to negotiate their own disputes on neutral grounds in a peaceful, non- violent method facilitated by a mediator. Through this process students can better...
  • AUTOMATIC TRANSFER SWITCHES - Russelectric

    AUTOMATIC TRANSFER SWITCHES - Russelectric

    ATS. If an acceptable window of voltage and frequency is not achieved, desired transfer will not happen. Example: ATS needs to return to utility after being in the engine generator (emergency) position… engine speed running erratically, no window achieved… switch...
  • SAFETY TALK Cold Stress When exposed to cold

    SAFETY TALK Cold Stress When exposed to cold

    SAFETY TALK. Cold Stress. Frostbite: Frostbite is an injury to the body that is caused by freezing. Frostbite causes a loss of feeling and color in the affected areas. It most often affects the nose, ears, cheeks, chin, fingers, or...