Lecture 02 Dr. Eng. Ibrahim El-Nahry Methods. 2 Learning Objectives Class Definition includes both methods and data properties Method Definition and Declaration.

Slides:



Advertisements
Similar presentations
 2005 Pearson Education, Inc. All rights reserved Introduction to Classes and Objects.
Advertisements

BBS514 Structured Programming (Yapısal Programlama)1 Functions and Structured Programming.
Chapter 7 User-Defined Methods. Chapter Objectives  Understand how methods are used in Java programming  Learn about standard (predefined) methods and.
Methods. int month; int year class Month Defining Classes A class contains data declarations (static and instance variables) and method declarations (behaviors)
Chapter 3 Function Basics Copyright © 2008 Pearson Addison-Wesley. All rights reserved.
Chapter 5 Functions.
Math class methods & User defined methods Introduction to Computers and Programming in JAVA: V
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 5 - Functions Outline 5.1Introduction 5.2Program.
 2007 Pearson Education, Inc. All rights reserved C Functions.
Introduction to Java Programming, 4E Y. Daniel Liang.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved COS240 O-O Languages AUBG,
CSC 200 Lecture 04 2/8/06 Matt Kayala. Learning Objectives  Predefined Functions  Those that return a value and those that don’t  Programmer-defined.
Differences between C# and C++ Dr. Catherine Stringfellow Dr. Stewart Carpenter.
Apply Sub Procedures/Methods and User Defined Functions
Introduction to Java Appendix A. Appendix A: Introduction to Java2 Chapter Objectives To understand the essentials of object-oriented programming in Java.
Methods Chapter 6. 2 Program Modules in Java What we call "functions" in C++ are called "methods" in Java Purpose Reuse code Modularize the program This.
METHODS Introduction to Systems Programming - COMP 1005, 1405 Instructor : Behnam Hajian
Chapter 6: User-Defined Functions I Instructor: Mohammad Mojaddam
Writing Classes (Chapter 4)
Advanced Programming LOOP.
Dale Roberts Procedural Programming using Java Dale Roberts, Lecturer Computer Science, IUPUI Department of Computer and.
More with Methods (parameters, reference vs. value, array processing) Corresponds with Chapters 5 and 6.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. C How To Program - 4th edition Deitels Class 05 University.
1 Introduction to C# Programming Console applications No visual components Only text output Two types MS-DOS prompt - Used in Windows 95/98/ME Command.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Functions.
1 Introduction Modules  Most computer programs solve much larger problem than the examples in last sessions.  The problem is more manageable and easy.
Methods in Java. Program Modules in Java  Java programs are written by combining new methods and classes with predefined methods in the Java Application.
Slide 1 Chapter 3 Function Basics. Slide 2 Learning Objectives  Predefined Functions  Those that return a value and those that don’t  Programmer-defined.
Procedural programming in Java Methods, parameters and return values.
1 Introduction to C# Programming Console applications No visual components Only text output Two types MS-DOS prompt - Used in Windows 95/98/ME Command.
Chapter 4 Introduction to Classes, Objects, Methods and strings
C# C1 CSC 298 Elements of C# code (part 1). C# C2 Style for identifiers  Identifier: class, method, property (defined shortly) or variable names  class,
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 5 - Functions Outline 5.1Introduction 5.2Program.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Functions Outline 5.1Introduction 5.2Program Modules.
C++ Programming Lecture 9 Functions – Part I By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department.
KIC/Computer Programming & Problem Solving 1.  Introduction  Program Modules in C  Math Library Functions  Functions  Function Definitions  Function.
Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 1 McGraw-Hill/Irwin Chapter 5 Creating Classes.
 2001 Prentice Hall, Inc. All rights reserved. 1 Chapter 5 – Control Structures: Part 2 Outline 5.1 Introduction 5.2 Essentials of Counter-Controlled.
 2001 Prentice Hall, Inc. All rights reserved. 1 Introduction to C# Part II.
Java™ How to Program, 9/e © Copyright by Pearson Education, Inc. All Rights Reserved.
Advanced Programming LOOP. 2 while Repetition Structure Repetition Structure –An action is to be repeated Continues while statement is true Ends when.
CSCI 3328 Object Oriented Programming in C# Chapter 6: Methods 1 Xiang Lian The University of Texas Rio Grande Valley Edinburg, TX 78539
1 Chapter 6 Methods. 2 Motivation Find the sum of integers from 1 to 10, from 20 to 30, and from 35 to 45, respectively.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 6: User-Defined Functions I.
Functions  A Function is a self contained block of one or more statements or a sub program which is designed for a particular task is called functions.
Classes Methods and Properties. Introduction to Classes and Objects In object-oriented programming terminology, a class is defined as a kind of programmer-defined.
 2001 Prentice Hall, Inc. All rights reserved. 1 Chapter 3 – Introduction to C# Programming Outline 3.1 Introduction 3.2 Simple Program: Printing a Line.
Chapter 3: User-Defined Functions I
 2005 Pearson Education, Inc. All rights reserved Introduction to Classes and Objects.
5.1 Introduction Problem Solving –Requires understanding of: Building blocks Program-construction principles BZUPAGES.COM.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 6: User-Defined Functions I.
C# Programming Methods.
 2002 Prentice Hall. All rights reserved. 1 Chapter 5 – Control Structures: Part 2 Outline 5.1Introduction 5.2 Essentials of Counter-Controlled Repetition.
CSIS 113A Lecture 5 Functions. Introduction to Functions  Building Blocks of Programs  Other terminology in other languages:  Procedures, subprograms,
CSCI 51 Introduction to Programming Dr. Joshua Stough February 24, 2009.
CMSC 104, Section 301, Fall Lecture 18, 11/11/02 Functions, Part 1 of 3 Topics Using Predefined Functions Programmer-Defined Functions Using Input.
BIL 104E Introduction to Scientific and Engineering Computing Lecture 4.
Chapter 6: User-Defined Functions I
3 Introduction to Classes and Objects.
Chapter 5 - Functions Outline 5.1 Introduction
Functions Declarations CSCI 230
Advanced Programming Chapter 7: Methods: A Deeper Look
METHODS AND BEHAVIORS AKEEL AHMED.
Advanced Programming Lecture 02: Introduction to C# Apps
Chapter 6 Methods: A Deeper Look
Group Status Project Status.
Chapter 3 – Introduction to C# Programming
Chapter 5 Methods.
Chapter 5 – Control Structures: Part 2
Visual Programming COMP-315
Presentation transcript:

Lecture 02 Dr. Eng. Ibrahim El-Nahry Methods

2 Learning Objectives Class Definition includes both methods and data properties Method Definition and Declaration. Math Class Methods Abstraction and Reuse The return Statement Objects Explicitly Creating Objects Creating and Accessing Objects Modifying Formal Arguments Call-By-Value Call- By-Reference

3 Introduction to Methods A complex problem is often easier to solve by dividing it into several smaller parts, each of which can be solved by itself. This is called structured programming. These parts are sometimes made into methods in C#. main() then uses these methods to solve the original problem.

4 Introduction to Methods Building Blocks of Programs Other terminology in other languages: Procedures, subprograms, functions In C#: methods I-P-O Input – Process – Output Basic subparts to any program Use methods for these ‘pieces’

5 Advantages of Methods Methods separate the concept (what is done) from the implementation (how it is done). Methods make programs easier to understand. Methods can be called several times in the same program, allowing the code to be reused.

6 Classes/Methods ( Predefined) C# Framework Class Library (FCL) defines many classes, e.g., Console MessageBox Int32 Math The definition of a class includes both methods and data properties: methods, e.g., Console.Write( ) Console.WriteLine( ) Int32.Parse( ) properties, e.g., Int32.MinValue Int32.MaxValue Math.PI Math.E

7 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 ( I-P-O) Example: invoking the WriteLine method of the Console class: Console.WriteLine ( "Whatever you are, be a good one.“ ); class methodInformation provided to the method (parameters) dot

8 Example: Math Class Methods

9 Programmer-Defined Class/Methods Write your own methods! Building blocks of programs Divide & Conquer Readability Re-use Your ‘definition’ can go in either: Same file as main() Separate file so others can use it, too

10 Components of Method Use 3 Pieces to using methods: Method Declaration Information for compiler To properly interpret calls Method Definition Actual implementation/code for what method does Method Call Transfer control to method

11 Methods Provide Abstraction and Reuse An abstraction hides (or ignores) the right details at the right time A method is abstract in that we don't really have to think about its internal details in order to use it e.g., we don't have to know how the WriteLine method works in order to invoke it Why abstraction? Divide and conquer Reuse Easier to understand

12 Method Declaration: Header A method declaration begins with a method header methodname returntype parameter list The parameter list specifies the type and name of each parameter The name of a parameter in the method declaration is called a formal argument class MyClass { static int SquareSum( int num1, int num2 ) … properties

13 Method Declaration: Body The method header is followed by the method body static int SquareSum(int num1, int num2) { int sum = num1 + num2; return sum * sum; } class MyClass { … … }

14 The return Statement The return type of a method indicates the type of value that the method sends back to the calling location A method that does not return a value has a void return type The return statement specifies the value that will be returned Its expression must conform to the return type

15 Calling a Method Each time a method is called, the actual arguments in the invocation are copied into the formal arguments static int SquareSum (int num1, int num2) { int sum = num1 + num2; return sum * sum; } int num = SquareSum (2, 3);

16 More Examples of Classes/Methods The Console class Console The Write and WriteLine methods The String class String The Format method: e.g., String.Format( “ {0:C} ”, 2.0 )

17 More Examples of Classes/Methods The MessageBox classMessageBox The Show method we will use has four parameters text to be displayed, caption, buttons, icon Argument 4: MessageBox Icon (Optional) Argument 3: OK dialog button. (Optional) Argument 2: Title bar string (Optional) Argument 1: Message to display

18 Sum.cs Program Output 1 // Sum.cs 2 // Summation with the for structure. 3 4 using System; 5 using System.Windows.Forms; 6 7 class Sum 8 { 9 static void Main( string[] args ) 10 { 11 int sum = 0; for ( int number = 2; number <= 100; number += 2 ) 14 sum += number; MessageBox.Show( "The sum is " + sum, 17 "Sum Even Integers from 2 to 100", 18 MessageBoxButtons.OK, 19 MessageBoxIcon.Information ); } // end method Main } // end class Sum Argument 4: MessageBox Icon (Optional) Argument 3: OK dialog button. (Optional) Argument 2: Title bar string (Optional) Argument 1: Message to display Displays a message box with an OK button Has the message box contain an information icon The caption of the message boxThe title of the message box

19 MessageBox Buttons

20 MessageBox Icons

21 1 // Interest 2 // Calculating compound interest, using MessageBox and Pow. 3 4 using System; 5 using System.Windows.Forms; 6 7 class Interest 8 { 9 static void Main( string[] args ) 10 { 11 decimal amount, principal = ( decimal ) ; 12 double rate =.05; 13 string output; output = "Year\tAmount on deposit\n"; for ( int year = 1; year <= 10; year++ ) 18 { 19 amount = principal * 20 ( decimal ) Math.Pow( rate, year ); output += year + "\t" + 23 String.Format( "{0:C}", amount ) + "\n"; 24 } MessageBox.Show( output, 27 "Compound Interest", 27 MessageBoxButtons.OK, 28 MessageBoxIcon.Information ); } // end method Main } // end class Interest Shows a message box that displays the output with a title of “Compound Interest” has an OK button and an information icon Loops through 10 times starting at 1 and ending at 10, adding 1 to the counter (year) each time Insert a TabFormats amount to have a currency formatting ($0.00)

22 Program Output

23 MaximumValue 1 // MaximumValue 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() ); Console.Write( "Enter second floating-point value: " ); 16 double number2 = Double.Parse( Console.ReadLine() ); Console.Write( "Enter third floating-point value: " ); 19 double number3 = Double.Parse( Console.ReadLine() ); // call method Maximum to determine largest value 22 double max = Maximum( number1, number2, number3 ); // display maximum value 25 Console.WriteLine("\nmaximum is: " + max ); } // end method Main The program gets three values from the user The three values are then passed to the Maximum method for use

24 Maximum Value Program Output // 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 ) ); } // end method Maximum } // end class MaximumValue Enter first floating-point value: 37.3 Enter second floating-point value: Enter third floating-point value: maximum is: The Maximum method receives 3 variables and returns the largest one The use of Math.Max uses the Max method in class Math. The dot operator is used to call it.

25 Class Methods ( Static Methods) Previously we use class mainly to define related methods together: For example all math related methods are defined in the Math class The methods we have seen are defined as static (or class) methods To make a method static, a programmer applies the static modifier to the method definition The result of each invocation of a class (static) method is completely determined by the actual parameters

26 Brief About Static Modifier In C# Static modifier used with the class, field, method, properties, operator, event and constructors. We can not use static modifier with indexers, destructors. When we use static modifier with the members then they are no more part of instance of a class. Static members are a part of class itself. Therefore, there is exactly only one copy of each static field in a class. Note the following: 1.A constant is implicitly a static member. 2.A static member cannot be referenced through an instance. 3.You cannot use the this keyword with a static class member.

27 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 object: objectName.MethodName( … );

Example: class Test { static int x = y; static int y = 5; static void Main() { Console.WriteLine(Test.x); Console.WriteLine(Test.y); Test.x = 99; Console.WriteLine(Test.x); } /* Output: */ 28

29 Objects Object An object has internal state This is called encapsulation Thus the action (method) may depend on both parameters and internal state.

30 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 a method on an object, we use the variable (not the class), e.g., Random generator1 = new Random(); int num = generate1.Next();

31 Example: the Random class Random Random () Random methods 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

The Rules for Accessing Static and Instance Members: class Test { int x; static int y; void F() { x = 1; // Ok y = 1; // Ok } static void G() { x = 1; // Error y = 1; // Ok } static void Main() { Test t = new Test(); t.x = 1; // Ok t.y = 1; // Error, cannot access static member through instance Test.x = 1; // Error, cannot access instance member through type Test.y = 1; // Ok } 32

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

34 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

35 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

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

37 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( “{0}d {1}h {2}m”, d, h, m ); }

38 1 // 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 } // original value can be changed and initialized 16 static void SquareOut( out int x ) 17 { 18 x = 6; 19 x = x * x; 20 } // x is passed by value (original value not changed) 23 static void Square( int x ) 24 { 25 x = x * x; 26 } static void Main( string[] args ) 29 { 30 // create a new integer value, set it to 5 31 int y = 5; 32 int z; // declare z, but do not initialize it 33 When passing a value by reference the value will be altered in the rest of the program as well Since x is passed as out the variable can then be initialed in the method Since not specified, this value is defaulted to being passed by value. The value of x will not be changed elsewhere in the program because a duplicate of the variable is created. Since the methods are void they do not need a return value.

39 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"; // values of y and z are passed by value 39 RefOutTest.SquareRef( ref y ); 40 RefOutTest.SquareOut( out z ); // 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"; // values of y and z are passed by value 50 RefOutTest.Square( y ); 51 RefOutTest.Square( z ); // values of y and z will be same as before because Square 54 // did not modify variables directly 55 string output3 = "After calling Square on both x and y, " + 56 "the values of y and z are:\n\n" + 57 "y: " + y + "\nz: " + z + "\n\n"; MessageBox.Show( output1 + output2 + output3, 60 "Using ref and out Parameters", MessageBoxButtons.OK, 61 MessageBoxIcon.Information ); } // end method Main } // end class RefOutTest The calling of the SquareRef and SquareOut methods The calling of the SquareRef and SquareOut methods by passing the variables by value

40

41 Summary 1 A method should provide a well-defined, easy-to- understand functionality 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 object: objectVariableName.MethodName( … );

42 Summary 2 Parameter Passing Call-By-Value For the simple data types if a modification on the formal argument has no effect on the actual argument Call- By-Reference If a modification on the formal argument can change the actual argument The ref keyword and the out keyword change a parameter to call-by-reference