CS 112 Introduction to Programming - PowerPoint PPT Presentation

1 / 28
About This Presentation
Title:

CS 112 Introduction to Programming

Description:

A method takes input (parameters), performs some actions, and (sometime) returns ... a list of (static) method declarations and (static) data fields ... – PowerPoint PPT presentation

Number of Views:41
Avg rating:3.0/5.0
Slides: 29
Provided by: Richar9
Category:

less

Transcript and Presenter's Notes

Title: CS 112 Introduction to Programming


1
CS 112 Introduction to Programming
  • Lecture 12
  • Method Overloading and Parameter Passing
  • Http//zoo.cs.yale.edu/classes/cs112/

2
Outline
  • Admin. and review
  • More about defining and using methods
  • Method header
  • Overloading and signature
  • Method parameter passing
  • Method body
  • Variable scope and duration

3
Admin.
  • Assignment 2
  • For how to generate random numbers, check the
    sample programs
  • RandomNumbers
  • RandomInt

4
Recap Methods
  • A method should provide a well-defined,
    easy-to-understand functionality
  • A method takes input (parameters), performs some
    actions, and (sometime) returns a value
  • Writing a custom method
  • Header
  • Properties ReturnType Name( Param1, Param2, )
  • Body
  • Contains the code of what the method does
  • Contains the return value if necessary
  • All methods must be defined inside of a class

5
MaximumValue.cs
  • 1 // Fig. 6.4 MaximumValue.cs
  • 2 // Finding the maximum of three doubles.
  • 3
  • 4 using System
  • 5
  • 6 class MaximumValue
  • 7
  • 8 // main entry point for application
  • 9 static void Main( string args )
  • 10
  • 11 // obtain user input and convert to
    double
  • 12 Console.Write( "Enter first
    floating-point value " )
  • 13 double number1 Double.Parse(
    Console.ReadLine() )
  • 14
  • 15 Console.Write( "Enter second
    floating-point value " )
  • 16 double number2 Double.Parse(
    Console.ReadLine() )
  • 17
  • 18 Console.Write( "Enter third
    floating-point value " )
  • 19 double number3 Double.Parse(
    Console.ReadLine() )

6
MaximumValue.cs Program Output
  • 28
  • 29 // Maximum method uses method Math.Max to
    help determine
  • 30 // the maximum value
  • 31 static double Maximum( double x, double
    y, double z )
  • 32
  • 33 return Math.Max( x, Math.Max( y, z )
    )
  • 34
  • 35 // end method Maximum
  • 36
  • 37 // end class MaximumValue

Enter first floating-point value 37.3 Enter
second floating-point value 99.32 Enter third
floating-point value 27.1928   maximum is 99.32
7
The Dual Roles of C Classes
  • Program modules
  • a list of (static) method declarations and
    (static) data fields
  • To make a method static, a programmer applies the
    static modifier to the method definition
  • The result of each invocation of a class method
    is completely determined by the actual parameters
    (and static fields of the class)
  • To use a static method ClassName.MethodName()
  • Blueprints for generating objects
  • Create an object
  • Call methods of the objectobjectName.MethodName(
    )

8
Explicitly Creating Objects
  • A class name can be used as a type to declare an
    object reference variable String title Random
    myRandom
  • An object reference variable holds the address of
    an object
  • No object has been created with the above
    declaration
  • The object itself must be created using the new
    keyword

9
Creating and Accessing Objects
  • We use the new operator to create an object

Random myRandom myRandom new Random()
This calls the Random constructor, which is a
special method that sets up the object
  • Creating an object is called instantiation
  • An object is an instance of a particular class
  • To call an (instance) method on an object, we use
    the variable (not the class), e.g.,
  • Random generator1 new Random()
  • int num generate1.Next()

10
Example the Random class
  • Some methods from the Random class

Random Random ()
int Next () // returns an integer
from 0 to Int32.MaxValue
int Next (int max) // returns an
integer from 0 upto but not including max
int Next (int min, int max) //
returns an integer from min upto but not
including max
double NextDouble ( ) // returns a
double number from 0 to 1
See RandomNumbers.cs
11
RandomInt.cs
  • 1 // Fig. 6.9 RandomInt.cs
  • 2 // Random integers.
  • 3
  • 4 using System
  • 5 using System.Windows.Forms
  • 6
  • 7 // calculates and displays 20 random
    integers
  • 8 class RandomInt
  • 9
  • 10 // main entry point for application
  • 11 static void Main( string args )
  • 12
  • 13 int value
  • 14 string output ""
  • 15
  • 16 Random randomInteger new Random()
  • 17
  • 18 // loop 20 times
  • 19 for ( int i 1 i lt 20 i )

12
RandomInt.cs Program Output
  • 31 MessageBox.Show( output, "20 Random
    Numbers from 1 to 6",
  • 32 MessageBoxButtons.OK,
    MessageBoxIcon.Information )
  • 33
  • 34 // end Main
  • 35
  • 36 // end class RandomInt

13
A Quick Summary
  • If a method is a static method
  • Call the method by ClassName.MethodName()
  • If a method of a class is not a static method,
    then it is an instance method
  • Create an object using the new operator
  • Call methods of the objectobjectVariableName.Met
    hodName()
  • We will study instance methods in more details
    next week

14
Outline
  • Admin. and review
  • More about using and defining methods
  • Method header
  • Overloading and signature
  • Method parameter passing

15
Method Overloading
  • The following lines use the WriteLine method for
    different data types
  • Console.WriteLine ("The total is")
  • double total 0
  • Console.WriteLine (total)
  • Method overloading is the process of using the
    same method name for multiple methods
  • Usually perform the same task on different data
    types
  • Example The WriteLine method is overloaded
  • WriteLine (String s)
  • WriteLine (int i)
  • WriteLine (double d)

16
Method Overloading Signature
  • The compiler must be able to determine which
    version of the method is being invoked
  • This is by analyzing the parameters, which form
    the signature of a method
  • The signature includes the number, type, and
    order of the parameters
  • The return type of the method is not part of the
    signature

17
Method Overloading
18
MethodOverload2.cs Program
Output
  • 1 // Fig. 6.19 MethodOverload2.cs
  • 2 // Overloaded methods with identical
    signatures and
  • 3 // different return types.
  • 4
  • 5 using System
  • 6
  • 7 class MethodOverload2
  • 8
  • 9 static int Square( double x )
  • 10
  • 11 return x x
  • 12
  • 13
  • 14 // second Square method takes same
    number,
  • 15 // order and type of arguments, error
  • 16 static double Square( double y )
  • 17
  • 18 return y y
  • 19

19
Outline
  • Admin. and review
  • More about defining and using methods
  • Method header
  • Overloading and signature
  • Method parameter passing

20
Recall Calling a Method
  • Each time a method is called, the actual
    arguments in the invocation are copied into the
    formal arguments

int num SquareSum (2, 3)
21
Parameters Modifying Formal Arguments
  • You can use the formal arguments (parameters) as
    variables inside the method
  • Question If a formal argument is modified inside
    a method, will the actual argument be changed?

static int Square ( int x ) x x x
return x
static void Main ( string args ) int x
8 int y Square( x ) Console.WriteLine
( x )
22
Parameter Passing
  • If a modification on the formal argument has no
    effect on the actual argument,
  • it is call by value
  • If a modification on the formal argument can
    change the actual argument,
  • it is call by reference

23
Call-By-Value and Call-By-Reference in C
  • Depend on the type of the formal argument
  • For the simple data types, it is call-by-value
  • Change to call-by-reference
  • The ref keyword and the out keyword change a
    parameter to call-by-reference
  • If a formal argument is modified in a method, the
    value is changed
  • The ref or out keyword is required in both method
    declaration and method call
  • ref requires that the parameter be initialized
    before enter a method while out requires that the
    parameter be set before return from a method

24
Example ref
static void Foo( int p ) p static void Main
( string args ) int x 8 Foo( x ) //
a copy of x is made Console.WriteLine( x )
static void Foo( ref int p ) p static void
Main ( string args ) int x 8 Foo(
ref x ) // x is ref Console.WriteLine( x )
See TestRef.cs
25
Example out
static void Split( int timeLate,
out int days, out int
hours, out minutes )
days timeLate / 10000 hours (timeLate /
100) 100 minutes timeLate 100
static void Main ( string args ) int d,
h, m Split( 12345, out d, out h, out m )
Console.WriteLine( 0d 1h 2m, d, h, m )
See TestOut.cs
26
RefOutTest.cs
  • 1 // Fig. 6.8 RefOutTest.cs
  • 2 // Demonstrating ref and out parameters.
  • 3
  • 4 using System
  • 5 using System.Windows.Forms
  • 6
  • 7 class RefOutTest
  • 8
  • 9 // x is passed as a ref int (original
    value will change)
  • 10 static void SquareRef( ref int x )
  • 11
  • 12 x x x
  • 13
  • 14
  • 15 // original value can be changed and
    initialized
  • 16 static void SquareOut( out int x )
  • 17
  • 18 x 6
  • 19 x x x

27
RefOutTest.cs
  • 34 // display original values of y and z
  • 35 string output1 "The value of y
    begins as "
  • 36 y ", z begins
    uninitialized.\n\n\n"
  • 37
  • 38 // values of y and z are passed by
    value
  • 39 RefOutTest.SquareRef( ref y )
  • 40 RefOutTest.SquareOut( out z )
  • 41
  • 42 // display values of y and z after
    modified by methods
  • 43 // SquareRef and SquareOut
  • 44 string output2 "After calling
    SquareRef with y as an "
  • 45 "argument and SquareOut with z as
    an argument,\n"
  • 46 "the values of y and z are\n\n"
  • 47 "y " y "\nz " z "\n\n\n"
  • 48
  • 49 // values of y and z are passed by
    value
  • 50 RefOutTest.Square( y )
  • 51 RefOutTest.Square( z )
  • 52

28
RefOutTest.cs Program Output
Write a Comment
User Comments (0)
About PowerShow.com