C# Programming: From Problem Analysis to Program Design

Slides:



Advertisements
Similar presentations
Chapter 7 User-Defined Methods. Chapter Objectives  Understand how methods are used in Java programming  Learn about standard (predefined) methods and.
Advertisements

Section 5 – Classes. Object-Oriented Language Features Abstraction –Abstract or identify the objects involved in the problem Encapsulation –Packaging.
An Introduction to Programming with C++ Fifth Edition
Road Map Introduction to object oriented programming. Classes
C# Programming: From Problem Analysis to Program Design1 Methods and Behaviors C# Programming: From Problem Analysis to Program Design 3rd Edition 3.
C# Programming: From Problem Analysis to Program Design1 Methods and Behaviors C# Programming: From Problem Analysis to Program Design 3rd Edition 3.
C# Programming: From Problem Analysis to Program Design1 Creating Your Own Classes C# Programming: From Problem Analysis to Program Design 3rd Edition.
C# Programming: From Problem Analysis to Program Design1 Arrays C# Programming: From Problem Analysis to Program Design 3 rd Edition 7.
Advanced Object-Oriented Programming Features
Terms and Rules Professor Evan Korth New York University (All rights reserved)
C# Programming: From Problem Analysis to Program Design1 Data Types and Expressions C# Programming: From Problem Analysis to Program Design 3rd Edition.
1 Fall 2007ACS-1903 Chapter 6: Classes Classes and Objects Instance Fields and Methods Constructors Overloading of Methods and Constructors Scope of Instance.
Chapter Objectives You should be able to describe: Object-Based Programming Classes Constructors Examples Common Programming Errors.
Chapter 11: Classes and Data Abstraction
Introduction to Methods
Java Methods By J. W. Rider. Java Methods Modularity Declaring methods –Header, signature, prototype Static Void Local variables –this Return Reentrancy.
1 Chapter Two Using Data. 2 Objectives Learn about variable types and how to declare variables Learn how to display variable values Learn about the integral.
Comp 248 Introduction to Programming Chapter 4 - Defining Classes Part A Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.
Introduction to Classes and Objects (Through Ch 5) Dr. John P. Abraham Professor UTPA.
CSM-Java Programming-I Spring,2005 Introduction to Objects and Classes Lesson - 1.
Writing Classes (Chapter 4)
COP INTERMEDIATE JAVA Designing Classes. Class Template or blueprint for creating objects. Their definition includes the list of properties (fields)
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
CSCI 3328 Object Oriented Programming in C# Chapter 3: Introduction to Classes and Objects UTPA – Fall
Chapter 11: Classes and Data Abstraction. C++ Programming: Program Design Including Data Structures, Fourth Edition2 Objectives In this chapter, you will:
PART I THE C# LANGUAGE Chapters 3 Reference: Professional C# 4 and.Net 4 by Bill Evjen, et al 1.
Tuc Goodwin  Object and Component-Oriented Programming  Classes in C#  Scope and Accessibility  Methods and Properties  Nested.
Chapter 10 Introduction to Classes
Chapter 4 -2 part Writing Classes 5 TH EDITION Lewis & Loftus java Software Solutions Foundations of Program Design © 2007 Pearson Addison-Wesley. All.
Java™ How to Program, 10/e © Copyright by Pearson Education, Inc. All Rights Reserved.
More About Objects and Methods Chapter 5. Outline Programming with Methods Static Methods and Static Variables Designing Methods Overloading Constructors.
Computing with C# and the.NET Framework Chapter 2 C# Programming Basics ©2003, 2011 Art Gittleman.
Chapter 4 Introduction to Classes, Objects, Methods and strings
1 Chapter Four Creating and Using Classes. 2 Objectives Learn about class concepts How to create a class from which objects can be instantiated Learn.
C# Programming: From Problem Analysis to Program Design1 4 Methods and Behaviors.
Programming with Microsoft Visual Basic 2012 Chapter 11: Classes and Objects.
2 Objectives You should be able to describe: Object-Based Programming Classes Constructors Examples Common Programming Errors.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 12: Classes and Data Abstraction.
Chapter 10: Classes and Data Abstraction. Objectives In this chapter, you will: Learn about classes Learn about private, protected, and public members.
CSci 162 Lecture 10 Martin van Bommel. Procedures vs Objects Procedural Programming –Centered on the procedures or actions that take place in a program.
Static. 2 Objectives Introduce static keyword –examine syntax –describe common uses.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X 1 Chapter 9 Objects and Classes.
Java Classes Chapter 1. 2 Chapter Contents Objects and Classes Using Methods in a Java Class References and Aliases Arguments and Parameters Defining.
Functions Math library functions Function definition Function invocation Argument passing Scope of an variable Programming 1 DCT 1033.
1/23/2016Assoc. Prof. Stoyan Bonev1 COS240 O-O Languages AUBG, COS dept Lecture 31 Title: C# Methods Reference: COS240 Syllabus.
Chapter 11: Advanced Inheritance Concepts. Objectives Create and use abstract classes Use dynamic method binding Create arrays of subclass objects Use.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 12: Classes and Data Abstraction.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Chapter 05: Classes and Data Abstraction.
Chapter 10: Classes and Data Abstraction. Classes Object-oriented design (OOD): a problem solving methodology Objects: components of a solution Class:
 Static  Example for Static Field  Example for Static Method  Math class methods  Casting  Scope of Declaration  Method Overloading  Constructor.
Microsoft Visual C#.NET: From Problem Analysis to Program Design1 Chapter 4 Methods and Behaviors Microsoft Visual C#.NET: From Problem Analysis to Program.
C# Programming: From Problem Analysis to Program Design1 Creating Your Own Classes C# Programming: From Problem Analysis to Program Design 4th Edition.
Classes CS 162 (Summer 2009). Parts of a Class Instance Fields Methods.
Chapter 5 Introduction to Defining Classes Fundamentals of Java.
Computer Programming II Lecture 5. Introduction to Object Oriented Programming (OOP) - There are two common programming methods : procedural programming.
3 Methods and Behaviors C# Programming: From Problem Analysis to Program Design1 4th Edition Methods and Behaviors 3.
Object-Oriented Programming (part 1 – Data Encapsulation)
Creating Your Own Classes
Reference: COS240 Syllabus
Introduction to Computing and Programming
C# Programming: From Problem Analysis to Program Design
Java Primer 1: Types, Classes and Operators
Reference: COS240 Syllabus
Chapter 3: Using Methods, Classes, and Objects
Creating Your Own Classes
Defining Classes and Methods
OBJECT ORIENTED PROGRAMMING II LECTURE 8 GEORGE KOUTSOGIANNAKIS
C# Programming: From Problem Analysis to Program Design
CIS 199 Final Review.
C# Programming: From Problem Analysis to Program Design
Presentation transcript:

C# Programming: From Problem Analysis to Program Design Methods and Behaviors 4 C# Programming: From Problem Analysis to Program Design 2nd Edition C# Programming: From Problem Analysis to Program Design

Chapter Objectives Become familiar with the components of a method Call class methods with and without parameters Use predefined methods in the Console and Math classes Write your own value and nonvalue-returning class methods (with and without parameters) Learn about the different methods and properties used for object-oriented development C# Programming: From Problem Analysis to Program Design

Chapter Objectives (continued) Write your own instance methods to include constructors, mutators, and accessors Call instance methods including constructors, mutators, and accessors Distinguish between value, ref, and out parameter types Work through a programming example that illustrates the chapter’s concepts C# Programming: From Problem Analysis to Program Design

Anatomy of a Method Methods defined inside classes Group program statements Based on functionality Called one or more times All programs consist of at least one method Main( ) User-defined method C# Programming: From Problem Analysis to Program Design

Required method /* SquareExample.cs Author: Doyle */ using System; namespace Square { public class SquareExample public static void Main( ) int aValue = 768; int result; result = aValue * aValue; Console.WriteLine(“{0} squared is {1}”, aValue, result); Console.Read( ); } Required method C# Programming: From Problem Analysis to Program Design

Anatomy of a Method (continued) Figure 4-1 Method components C# Programming: From Problem Analysis to Program Design

Modifiers Appear in method headings Appear in the declaration heading for classes and other class members Indicate how it can be accessed Types of modifiers Static Access C# Programming: From Problem Analysis to Program Design

Static Modifier Indicates member belongs to the type itself rather than to a specific object of a class Main( ) must include static in heading Members of the Math class are static public static double Pow(double, double) Methods that use the static modifier are called class methods Instance methods require an object C# Programming: From Problem Analysis to Program Design

Access Modifiers public protected internal protected internal private C# Programming: From Problem Analysis to Program Design

Level of Accessibility C# Programming: From Problem Analysis to Program Design

Return Type Indicates what type of value is returned when the method is completed Always listed immediately before method name void No value being returned return statement Required for all non-void methods Compatible value C# Programming: From Problem Analysis to Program Design

Return Type (continued) public static double CalculateMilesPerGallon (int milesTraveled, double gallonsUsed) { return milesTraveled / gallonsUsed; } Compatible value (double) returned C# Programming: From Problem Analysis to Program Design

Method Names Follow the rules for creating an identifier Examples Pascal case style Action verb or prepositional phrase Examples CalculateSalesTax( ) AssignSectionNumber( ) DisplayResults( ) InputAge( ) ConvertInputValue( ) C# Programming: From Problem Analysis to Program Design

Parameters Supply unique data to method Appear inside parentheses Include data type and an identifier In method body, reference values using identifier name Parameter refers to items appearing in the heading Argument for items appearing in the call Formal parameters Actual arguments C# Programming: From Problem Analysis to Program Design

Parameters (continued) public static double CalculateMilesPerGallon (int milesTraveled, double gallonsUsed) { return milesTraveled / gallonsUsed; } Call to method inside Main( ) method Console.WriteLine(“Miles per gallon = {0:N2}”, CalculateMilesPerGallon(289, 12.2)); Two formal parameters Actual arguments C# Programming: From Problem Analysis to Program Design

Parameters (continued) Like return types, parameters are optional Keyword void not required (inside parentheses) – when there are no parameters public void DisplayMessage( ) { Console.Write(”This is “); Console.Write(”an example of a method ”); Console.WriteLine(“body. ”); return; // no value is returned } C# Programming: From Problem Analysis to Program Design

Method Body Enclosed in curly braces Include statements ending in semicolons Declare variables Do arithmetic Call other methods Value-returning methods must include return statement C# Programming: From Problem Analysis to Program Design

Calling Class Methods Invoke a method Call to method that returns no value [qualifier].MethodName(argumentList); Qualifier Square brackets indicate optional class or object name Call to method does not include data type Use Intellisense C# Programming: From Problem Analysis to Program Design

Predefined Methods Extensive class library Console class Overloaded methods Write( ) WriteLine( ) Read( ) Not overloaded Returns an integer C# Programming: From Problem Analysis to Program Design

Intellisense Figure 4-2 Console class members After typing the dot, list of members pops up After typing the dot, list of members pops up Method signature(s) and description Method signature(s) and description 3-D fuchsia colored box —methods aqua colored box — fields (not shown) Figure 4-2 Console class members C# Programming: From Problem Analysis to Program Design

Intellisense Display Figure 4-3 IntelliSense display string argument expected string parameter 18 different Write( ) methods Figure 4-3 IntelliSense display C# Programming: From Problem Analysis to Program Design

Intellisense Display (continued) Figure 4-4 Console.Read ( ) signature Figure 4-5 Console.ReadLine ( ) signature C# Programming: From Problem Analysis to Program Design

Call Read( ) Methods int aNumber; Console.Write(“Enter a single character: ”); aNumber = Console.Read( ); Console.WriteLine(“The value of the character entered: ” + aNumber); Enter a single character: a The value of the character entered: 97 C# Programming: From Problem Analysis to Program Design

Call Read( ) Methods (continued) int aNumber; Console.WriteLine(“The value of the character entered: “ + (char) Console.Read( )); Enter a single character: a The value of the character entered: a C# Programming: From Problem Analysis to Program Design

Call ReadLine( ) Methods More versatile than the Read( ) Returns all characters up to the enter key Not overloaded Always returns a string String value must be parsed C# Programming: From Problem Analysis to Program Design

Call Parse( ) Predefined static method All numeric types have a Parse( ) method double.Parse(“string number”) int.Parse(“string number”) char.Parse(“string number”) bool.Parse(“string number”) Expects string argument Argument must be a number – string format Returns the number (or char or bool) C# Programming: From Problem Analysis to Program Design

/* AgeIncrementer.cs Author: Doyle */ using System; namespace AgeExample { public class AgeIncrementer public static void Main( ) int age; string aValue; Console.Write(“Enter your age: “); aValue = Console.ReadLine( ); age = int.Parse(aValue); Console.WriteLine(“Your age next year” + “ will be {0}”, ++age); Console.Read( ); } } } C# Programming: From Problem Analysis to Program Design

/* SquareInputValue.cs Author: Doyle */ using System; namespace Square { class SquareInputValue static void Main( ) string inputStringValue; double aValue, result; Console.Write(“Enter a value to be squared: ”); inputStringValue = Console.ReadLine( ); aValue = double.Parse(inputStringValue); result = Math.Pow(aValue, 2); Console.WriteLine(“{0} squared is {1}”, aValue, result); } C# Programming: From Problem Analysis to Program Design

Call Parse( ) (continued) string sValue = “True”; Console.WriteLine (bool.Parse(sValue)); // displays True string strValue = “q”; Console.WriteLine(char.Parse(strValue)); // displays q C# Programming: From Problem Analysis to Program Design

Call Parse( ) with Incompatible Value Console.WriteLine(char.Parse(sValue)); when sValue referenced “True” Figure 4-6 System.FormatException run-time error C# Programming: From Problem Analysis to Program Design

Convert Class More than one way to convert from one base type to another System namespace — Convert class — static methods Convert.ToDouble( ) Convert.ToDecimal( ) Convert.ToInt32( ) Convert.ToBoolean( ) Convert.ToChar( ) int newValue = Convert.ToInt32(stringValue); C# Programming: From Problem Analysis to Program Design

C# Programming: From Problem Analysis to Program Design

C# Programming: From Problem Analysis to Program Design

C# Programming: From Problem Analysis to Program Design

Math( ) Class Each call returns a value double aValue = 78.926; double result1, result2; result1 = Math.Floor(aValue); // result1 = 78 result2 = Math.Sqrt(aValue); // result2 = 8.88403061678651 Console.Write(“aValue rounded to 2 decimal places” + “ is {0}”, Math.Round(aValue, 2)); aValue rounded to 2 decimal places is 78.93 C# Programming: From Problem Analysis to Program Design

Method Calls That Return Values In an assignment statement Line 1 int aValue = 200; Line 2 int bValue = 896; Line 3 int result; Line 4 result = Math.Max(aValue, bValue); // result = 896 Line 5 result += bValue * Line 6 Math.Max(aValue, bValue) – aValue; // result = 896 + (896 * 896 - 200) (result = 803512) Line 7 Console.WriteLine(“Largest value between {0} ” Line 8 + “and {1} is {2}”, aValue, bValue, Line 9 Math.Max(aValue, bValue)); Part of arithmetic expression Argument to another method call C# Programming: From Problem Analysis to Program Design

Writing Your Own Class Methods [modifier(s)] returnType  MethodName ( parameterList ) {  // body of method - consisting of executable statements    } void Methods Simplest to write No return statement C# Programming: From Problem Analysis to Program Design

Writing Your Own Class Methods – void Types public static void DisplayInstructions( ) { Console.WriteLine(“This program will determine how ” + “much carpet to purchase.”); Console.WriteLine( ); Console.WriteLine(“You will be asked to enter the ” + “ size of the room and ”); Console.WriteLine(“the price of the carpet, ” + ”in price per square yards.”); } A call to this method looks like: DisplayInstructions( ); C# Programming: From Problem Analysis to Program Design

Writing Your Own Class Methods – void Types (continued) public static void DisplayResults(double squareYards, double pricePerSquareYard) { Console.Write(“Total Square Yards needed: ”); Console.WriteLine(“{0:N2}”, squareYards); Console.Write(“Total Cost at {0:C} “, pricePerSquareYard); Console.WriteLine(“ per Square Yard: {0:C}”, (squareYards * pricePerSquareYard)); } static method called from within the class where it resides To invoke method – DisplayResults(16.5, 18.95); C# Programming: From Problem Analysis to Program Design

Value-Returning Method Has a return type other than void Must have a return statement Compatible value Zero, one, or more data items may be passed as arguments Calls can be placed: In assignment statements In output statements In arithmetic expressions Or anywhere a value can be used C# Programming: From Problem Analysis to Program Design

Value-Returning Method (continued) public static double GetLength( ) { string inputValue; int feet, inches; Console.Write(“Enter the Length in feet: ”); inputValue = Console.ReadLine( ); feet = int.Parse(inputValue); Console.Write(“Enter the Length in inches: “); inches = int.Parse(inputValue); return (feet + (double) inches / 12); } Return type→ double double returned C# Programming: From Problem Analysis to Program Design

CarpetExampleWithClassMethods /* CarpetExampleWithClassMethods.cs */ using System; namespace CarpetExampleWithClassMethods { public class CarpetWithClassMethods public static void Main( ) double roomWidth, roomLength, pricePerSqYard, noOfSquareYards; DisplayInstructions( ); // Call getDimension( ) to get length roomLength = GetDimension(“Length”); C# Programming: From Problem Analysis to Program Design

CarpetExampleWithClassMethods (continued) /* CarpetExampleWithClassMethods.cs */ using System; namespace CarpetExampleWithClassMethods { public class CarpetWithClassMethods C# Programming: From Problem Analysis to Program Design

double roomWidth, roomLength, pricePerSqYard, noOfSquareYards; public static void Main( ) { double roomWidth, roomLength, pricePerSqYard, noOfSquareYards; DisplayInstructions( ); // Call getDimension( ) to get length roomLength = GetDimension(“Length”); roomWidth = GetDimension(“Width”); pricePerSqYard = GetPrice( ); noOfSquareYards = DetermineSquareYards(roomWidth, roomLength); DisplayResults(noOfSquareYards, pricePerSqYard); } C# Programming: From Problem Analysis to Program Design

public static void DisplayInstructions( ) { Console.WriteLine(“This program will determine how much " + “carpet to purchase.”); Console.WriteLine( ); Console.WriteLine("You will be asked to enter the size of ” + “the room "); Console.WriteLine(“and the price of the carpet, in price per” + “ square yds.”); } C# Programming: From Problem Analysis to Program Design

public static double GetDimension(string side ) { string inputValue; // local variables int feet, // needed only by this inches; // method Console.Write("Enter the {0} in feet: ", side); inputValue = Console.ReadLine( ); feet = int.Parse(inputValue); Console.Write("Enter the {0} in inches: ", side); inches = int.Parse(inputValue); // Note: cast required to avoid int division return (feet + (double) inches / 12); } C# Programming: From Problem Analysis to Program Design

string inputValue; // local variables double price; public static double GetPrice( ) { string inputValue; // local variables double price; Console.Write(“Enter the price per Square Yard: "); inputValue = Console.ReadLine( ); price = double.Parse(inputValue); return price; } C# Programming: From Problem Analysis to Program Design

public static double DetermineSquareYards (double width, double length) { const int SQ_FT_PER_SQ_YARD = 9; double noOfSquareYards; noOfSquareYards = length * width / SQ_FT_PER_SQ_YARD; return noOfSquareYards; } public static double DeterminePrice (double squareYards, double pricePerSquareYard) return (pricePerSquareYard * squareYards); C# Programming: From Problem Analysis to Program Design

public static void DisplayResults (double squareYards, double pricePerSquareYard) { Console.WriteLine( ); Console.Write(“Square Yards needed: ”); Console.WriteLine("{0:N2}", squareYards); Console.Write("Total Cost at {0:C} ", pricePerSquareYard); Console.WriteLine(“ per Square Yard: {0:C}”, DeterminePrice(squareYards, pricePerSquareYard)); } } // end of class } // end of namespace C# Programming: From Problem Analysis to Program Design

CarpetExampleWithClassMethods (continued) Figure 4-7 Output from CarpetExampleWithClassMethods C# Programming: From Problem Analysis to Program Design

The Object Concept Class Entity Abstraction Attributes (data) Behaviors (processes on the data) Private member data (fields) Public method members C# Programming: From Problem Analysis to Program Design

Writing Your Own Instance Methods Do not use static keyword Static – class method Constructor Do not return a value void is not included Same identifier as the class name Overloaded methods Default constructor No arguments C# Programming: From Problem Analysis to Program Design

Calling the Constructor Default values are assigned to variables of the value types when no arguments are sent C# Programming: From Problem Analysis to Program Design

Writing Your Own Instance Methods (continued) Accessor (getter) Returns the current value Standard naming convention → prefix with “get” Accessor for noOfSquareYards is GetNoOfSquareYards( ) Mutators (setters) Normally includes one parameter Method body → single assignment statement Standard naming convention → prefix with ”Set” C# Programming: From Problem Analysis to Program Design

Accessor and Mutator Examples public double GetNoOfSquareYards( ) { return noOfSquareYards; } public void SetNoOfSquareYards(double squareYards) noOfSquareYards = squareYards; Mutator C# Programming: From Problem Analysis to Program Design

Properties Looks like a data field More closely aligned to methods Standard naming convention in C# for properties Use the same name as the instance variable or field, but start with uppercase character C# Programming: From Problem Analysis to Program Design

Calling Instance Methods Calling the Constructor ClassName objectName = new ClassName(argumentList); or ClassName objectName; objectName = new ClassName(argumentList); Keyword new used as operator to call constructor methods CarpetCalculator plush = new CarpetCalculator ( ); CarpetCalculator pile = new CarpetCalculator (37.90, 17.95); CarpetCalculator berber = new CarpetCalculator (17.95); C# Programming: From Problem Analysis to Program Design

Calling Accessor and Mutator Methods Method name is preceded by the object name berber.SetNoOfSquareYards(27.83); Console.WriteLine(“{0:N2}”, berber.GetNoOfSquareYards( )); Using properties PropertyName = value; and Console.Write(“Total Cost at {0:C} ”, berber.Price); C# Programming: From Problem Analysis to Program Design

ToString( ) method All user-defined classes inherit four methods from the object class ToString( ) Equals( ) GetType( ) GetHashCode( ) ToString( ) method is called automatically by several methods Write( ) WriteLine( ) methods Can also invoke or call the ToString( ) method directly C# Programming: From Problem Analysis to Program Design

ToString( ) method (continued) Returns a human-readable string Can write a new definition for the ToString( ) method to include useful details public override string ToString( ) { // return string value } Keyword override added to provide new implementation details C# Programming: From Problem Analysis to Program Design

Types of Parameters Call by value Other types of parameters Copy of the original value is made Other types of parameters ref out params ref and out cause a method to refer to the same variable that was passed into the method C# Programming: From Problem Analysis to Program Design

Types of Parameters (continued) Figure 4-10 Call by reference versus value C# Programming: From Problem Analysis to Program Design

RealEstateInvestment Example Figure 4-12 Problem specification for RealEstateInvestment example C# Programming: From Problem Analysis to Program Design

Data for the RealEstateInvestment Example C# Programming: From Problem Analysis to Program Design

RealEstateInvestment Example (continued) Figure 4-13 Prototype C# Programming: From Problem Analysis to Program Design

RealEstateInvestment Example (continued) Figure 4-14 Class diagrams C# Programming: From Problem Analysis to Program Design

RealEstateInvestment Example (continued) C# Programming: From Problem Analysis to Program Design

RealEstateInvestment Example (continued) Figure 4-15 Structured English for the RealEstateInvestment example C# Programming: From Problem Analysis to Program Design

Chapter Summary Components of a method Class methods Parameters Predefined methods Value and nonvalue-returning methods C# Programming: From Problem Analysis to Program Design

Chapter Summary (continued) Properties Instance methods Constructors Mutators Accessors Types of parameters C# Programming: From Problem Analysis to Program Design