Presentation is loading. Please wait.

Presentation is loading. Please wait.

Jozef Goetz, 2015 1  2014 Pearson Education, Inc. All rights reserved.  2002 Prentice Hall. All rights reserved. expanded by J. Goetz, 2015 credits:

Similar presentations


Presentation on theme: "Jozef Goetz, 2015 1  2014 Pearson Education, Inc. All rights reserved.  2002 Prentice Hall. All rights reserved. expanded by J. Goetz, 2015 credits:"— Presentation transcript:

1

2 Jozef Goetz, 2015 1  2014 Pearson Education, Inc. All rights reserved.  2002 Prentice Hall. All rights reserved. expanded by J. Goetz, 2015 credits:

3 Jozef Goetz, 2015 2  Your public servants serve you right. Adlai E. Stevenson  Nothing can have value without being an object of utility. Karl Marx  Knowing how to answer one who speaks, To reply to one who sends a message. Amenemope  You will see something new. Two things. And I call them Thing One and Thing Two. Dr. Theodor Seuss Geisel

4 Jozef Goetz, 2015 3 OBJECTIVES In this chapter you will learn: 1.What classes, objects, methods and instance variables are. 2.How to declare a class and use it to create an object. 3.How to implement a class’s behaviors as methods. 4.How to implement a class’s attributes as instance variables and properties. 5.How to call an object’s methods to make the methods perform their tasks. 6.The differences between instance variables of a class and local variables of a method. 7.How to use a constructor to ensure that an object’s data is initialized when the object is created. 8.The differences between value types and reference types.

5 Jozef Goetz, 2015 4 4.1 Introduction 4.2 Classes, Objects, Methods, Properties and Instance Variables 4.3 Declaring a Class with a Method and Instantiating an Object of a Class 4.4 Declaring a Method with a Parameter 4.5 Instance Variables and Properties 4.6 UML Class Diagram with a Property 4.7 Software Engineering with Properties and set and get Accessors 4.8Auto-implemented Properties 4.9 Value Types vs. Reference Types 4.10 Initializing Objects with Constructors 4.11 Floating-Point Numbers and Type decimal Chapter 4 Introduction to Classes and Objects

6 Jozef Goetz, 2015 5 4.1 Introduction  Classes Properties Methods Constructors  We will explain the concepts of classes using a real-world example.

7 Jozef Goetz, 2015 6 4.2 Classes, Objects, Methods, Properties and Instance Variables  A car begins as engineering drawings, similar to the blueprints used to design a house.  Before you can drive a car, it must be built from the engineering drawings that describe it.  An accelerator pedal “ hides ” the complex mechanisms that actually make the car go faster. This enables people with little or no knowledge of how engines works to drive a car easily.

8 Jozef Goetz, 2015 7 4.2 Classes, Objects, Methods, Properties and Instance Variables  A class is used to house a method, just as a car’s drawings house the design of an accelerator pedal.  Class provides one or more methods.  A class that represents a bank account might contain one method to deposit money in an account, another to withdraw money from an account and a third to inquire what the current account balance is.

9 Jozef Goetz, 2015 8 4.2 Classes, Objects, Methods, Properties and Instance Variables  Method represents task in a program Describes the mechanisms that actually perform its tasks Hides from its user the complex tasks that it performs Method call tells method to perform its task  Just as someone has to build a car from its engineering drawings before you can actually drive it, you must build an object of a class before you can perform the tasks the class describes.  You send messages to an object by making method calls.

10 Jozef Goetz, 2015 9 4.2 Classes, Objects, Methods, Properties and Instance Variables  A car also has many attributes, such as  its color,  the number of doors,  the amount of gas in its tank,  its current speed and  its total miles driven.  Every car maintains its own attributes.  Attributes are specified by the class’s instance variables.  Classes contain one or more attributes Specified by instance variables Carried with the object as it is used

11 Jozef Goetz, 2015 10 4.2 Classes, Objects, Methods, Properties and Instance Variables (Cont.)  Attributes are not necessarily accessible directly. Customers talk to a bank teller or check personalized online bank accounts to obtain their account balance.  Similarly, you can use get accessors and set accessors to manipulate attributes.

12 Jozef Goetz, 2015 11 4.3 Declaring a Class with a Method and Instantiating an Object of a Class  Select File > New Project... and create a GradeBook Console Application p.109. Delete all the code and replace it by the code in Fig. 4.1  Class GradeBook Keyword public is an access modifier Class declarations include:  Access modifier  Keyword class  Pair of left and right braces public class GradeBook { }

13 Jozef Goetz, 2015 12 Outline  GradeBook.cs The method header for DisplayMessage()  Class GradeBook Method declarations  Keyword public indicates method is available to the public  Keyword void indicates that there is no return type  Methods without void return results  method header: –access modifier, –return type, –name of method and –parentheses comprise  Naming convention is to capitalize the first letter of every word

14 Jozef Goetz, 2015 13 4.3 Declaring a Class with a Method and Instantiating an Object of a Class (Cont.)  The method declaration begins with public to indicate that the method can be called from outside the class declaration’s body.  Keyword void - known as the method’s return type — indicates that this method will not return information to its calling method.  When a method specifies a return type other than void, the method returns a result to its calling method. int result = Square( 2 );  The body of a method contains statement(s) that perform the method’s task.

15 Jozef Goetz, 2015 14 4.3 Declaring a Class with a Method and Instantiating an Object of a Class (Cont.)  To add a class, right click the project name in the Solution Explorer and select Add > New Item….  In the Add New Item dialog, select Code File and enter the name of your new file GradeBookTest.cs

16 Jozef Goetz, 2015 15 4.3 Declaring a Class with a Method and Instantiating an Object of a Class (Cont.)  Class GradeBookTest Any class that contains a Main method can be used to execute an application static method is special because it can be called without first creating object of the class C# is extensible  Programmers can create new classes Class instance creation expression  Keyword new  Then name of class to create and parentheses Calling a method  Object’s name, then dot separator (. )  Then method’s name and parentheses –Ex. myGradeBook.DisplayMessage();

17 Jozef Goetz, 2015 16 Outline  GradeBookTest.cs UML class diagram indicating that class GradeBook has a public DisplayMessage operation. Use class instance creation expression to create object of class GradeBook Call method DisplayMessage using GradeBook object  Any class that contains a Main method can be used to execute an application.  A static method can be called without creating an object of the class.

18 Jozef Goetz, 2015 17 Fig. 4.3 | UML class diagram indicating that class GradeBook has a public DisplayMessage operation. Class name: GradeBook ------------------------------------------------------------ list of variable declarations and properties count : int = 500 + CourseName : String ------------------------------------------------------------ list of methods: + GradeBook ( name : string) + DisplayMessage() - Helper() + IsStudentPassed( name: string) : bool  UML class diagrams (Fig. 4.3) helps you design a class Top compartment contains name of the class Middle compartment contains class’s attributes or instance variables Bottom compartment contains class’s operations or methods  Plus sign indicates public methods  The plus sign ( + ) indicates that DisplayMessage is a public operation.

19 Jozef Goetz, 2015 18 Outline  GradeBook.cs Welcome to the grade book for CS101 Introduction to C# Programming! Method header DisplayMessage that takes a courseName argument of type string  Parameters specified in method’s parameter list Part of method header Uses a comma-separated list A method call supplies values called arguments Additional information passed to a method <= UML class diagram (Fig. 4.6) Parameters specified by parameter name followed by a colon and parameter type

20 Jozef Goetz, 2015 19 4.4 Declaring a Method with a Parameter (Cont.)  The method’s parameter list is located in the parentheses that follow the method name.  Empty parentheses indicate that a method does not require any parameters.  The argument value in the call is assigned to the corresponding parameter in the method header.

21 Jozef Goetz, 2015 20 Outline  GradeBookTest.cs Call ReadLine method to read a line of input and assigns it to nameOfCourse Call DisplayMessage with an argument Console.ReadLine reads a line of input

22 Jozef Goetz, 2015 21 Software Engineering Observation 4.1  Normally, objects are created with new. One exception is a string literal that is contained in quotes, such as " hello ". String literals are references to string objects that are implicitly created by C#.

23 Jozef Goetz, 2015 22 Common Programming Error 4.1 - 4.2  A compilation error occurs if the # of arguments in a method call does not match the # of parameters in the method declaration.  A compilation error occurs if the types of the arguments in a method call are not consistent with the types of the corresponding parameters in the method declaration.

24 Jozef Goetz, 2015 23 Fig. 4.6 | UML class diagram indicating that class GradeBook has a public DisplayMessage operation with a courseName parameter of type string. UML class diagram (Fig. 4.6) Parameters specified by parameter name followed by a colon and parameter type

25 Jozef Goetz, 2015 24 4.4 Declaring a Method with a Parameter (Cont.)  Using System Indicates to the compiler that the application uses classes in a namespace System By default, classes compiled in same project is considered in the same namespace Any classes not explicitly placed in a namespace are implicitly placed in the global namespace. Without using, we would write the class’s fully qualified class name: System.Console.WriteLine( "Please enter the course name:" );

26 Jozef Goetz, 2015 25 4.5 Instance Variables and Properties  Variables declared in the body of method Called local variables When a method terminates, the values of its local variables are lost. Can only be used within that method  Variables declared in a class declaration Called attributes, fields or instance variables Each object of the class has a separate instance of the variable - own copy of an attribute

27 Jozef Goetz, 2015 26 Outline  GradeBook.cs Instance variable courseName get accessor for property courseName set accessor for property courseName  Property Declaration Declaration consist of  an access modifier,  type, and  name get and set allows you to access and modify private variables outside of the class, respectively Contain a get accessor, set accessor, or both After defining a property, you can use it like a variable  get and set Accessors get accessor contains a return statement set accessor contains a variable = value  value implicitly declared

28 Jozef Goetz, 2015 27 4.5 Instance Variables and Properties (Cont.)  private keyword Used for most instance variables private variables and methods are accessible only to methods of the class in which they are declared Declaring instance variables private is known as information hiding

29 Jozef Goetz, 2015 28 4.5 Instance Variables and Properties (Cont.)  Default initial value Provided for all fields not initialized  0 for numeric/value type variables  null for String s and reference types

30 Jozef Goetz, 2015 29 Outline  GradeBook.cs Output: Initial course name is: '' Please enter the course name: CS101 Introduction to C# Programming Welcome to the grade book for CS101 Introduction to C# Programming! Call the get accessor

31 Jozef Goetz, 2015 30 Outline  GradeBookTest.cs Output: Initial course name is: '' Please enter the course name: CS101 Introduction to C# Programming Welcome to the grade book for CS101 Introduction to C# Programming! 22 23 // 4. display welcome message after specifying course name 24 myGradeBook.DisplayMessage(); 25 } // end Main 26 } // end class GradeBookTest Call get accessor of CourseName Call set accessor of CourseName

32 Jozef Goetz, 2015 31 Software Engineering Observation 4.2  Precede every field and method declaration with an access modifier.  As a rule of thumb, instance variables should be declared private and methods and properties should be declared public it is appropriate to declare certain methods private, if they will be accessed only by other methods of the class easier to debug b/c the private instance variables are accessible only to these method and properties  If the access modifier is omitted before a member of a class, the member is implicitly declared private by default.

33 Jozef Goetz, 2015 32 Good Programming Practice 4.1  list the fields of a class first, so that, as you read the code, you see the names and types of the variables before you see them used in the methods of the class. It is possible to list the class’s fields anywhere in the class outside its method declarations, but scattering them can make code difficult to read. 6 public class GradeBook 7{7{ 8 private string courseName; // course name for this GradeBook 10 // property to get and set the course name 11 public string CourseName 12 { 13 get - - - - - - - - -

34 Jozef Goetz, 2015 33 Good Programming Practice 4.2  Placing a blank line between method and property declarations enhances application readability.

35 Jozef Goetz, 2015 34 Fig. 4.9 | UML class diagram indicating that class GradeBook has a public CourseName property of type string and one public method. 4.6 UML Class Diagram with Property  UML Diagram Model properties in the UML as attributes:  Public is indicated by the “+” sign  > in guillemets  Property’s name “:” property’s type Modeling private instance variables that are not properties: Attribute’s name “:” attribute’s type  Private is indicated by the “-” sign

36 Jozef Goetz, 2015 35 Instance Variables and Properties (Cont.) We need to provide controlled ways for programmers to “get” and “set” the value of an instance variable.  Properties contain get and set accessors that handle the details of returning and modifying data. After defining a property, you can use it like a variable in your code.

37 Jozef Goetz, 2015 36 4.7 Software Engineering with Properties and set and get Accessors  Public variable can be read or written by any property or method  Private variables can only be access indirectly through the class’s non-private properties Class is able to control how the data is set or returned Allows for data validation  Properties of a class should use class’s own methods (i.e. helpers methods) to manipulate the class’s private instance variables Creates more robust class

38 Jozef Goetz, 2015 37 Software Engineering Observation 4.3  Accessing private data through set and get accessors 1.not only protects the instance variables from receiving invalid values, but 2.also hides the internal representation of the instance variables from that class’s clients.  Thus, if representation of the data changes often to reduce the amount of required storage or to improve performance,  only the properties’ implementations need to change - the clients’ implementations need not change as long as the services (public methods) provided by the properties are preserved.

39 Jozef Goetz, 2015 38 Notice:  that CourseName ’s get accessor simply returns courseName ’s value and  the set accessor simply assigns a value to the instance variable.  For such cases, C# now provides automatically implemented properties. public string CourseName { get; set; } Unlike a user-defined property, an auto-implemented property, must have both a get and a set accessor  If you later decide to implement other logic in the get or set accessors, you can simply reimplement the property. 4.8 Auto-implemented Properties

40 Jozef Goetz, 2015 39 Figure 4.12 redefines (Figure 4.7 p.117) class GradeBook with an auto-implemented CourseName property. Outline GradeBook.cs Fig. 4.12 | GradeBook class with an auto-implemented property. Declaring the auto- implemented property. Implicitly obtaining the property’s value.

41 Jozef Goetz, 2015 40 The unchanged test program (Fig. 4.8) shows that the auto-implemented property works identically. Outline GradeBookTest.cs (1 of 2 ) Fig. 4.8 | Create and manipulate a GradeBook object. (Part 1 of 2).

42 Jozef Goetz, 2015 41 Outline GradeBookTest.cs (2 of 2 ) Fig. 4.8 | Create and manipulate a GradeBook object. (Part 2 of 2).

43 Jozef Goetz, 2015 42 4.9 Value Types vs. Reference Types  Types in C# Value Types (Simple Types except String )  Contains a value of that type  List of Simple Types in Appendix B p. 952 Reference Types (sometimes called non-simple types)  Objects –Default value of null  Used to invoke an object’s methods and properties

44 Jozef Goetz, 2015 43  Fig.4.10 – 4.11 Value and reference type variable

45 Jozef Goetz, 2015 44 Software Engineering Observation 4.4  A variable’s declared type (e.g., int, double or GradeBook ) indicates whether the variable is of a value or a reference type.  If a variable’s type is not one of 13 simple types, or an enum or a struct type, then it is a reference type. For example, Account account1 indicates that account1 is a variable that can refer to an Account object.

46 Jozef Goetz, 2015 45 4.10 Initializing Objects with Constructors  Constructors 1.Initialize an object of a class 2.Constructors called to perform the initialization when keyword new is followed by the class name and parentheses 3.the compiler provides a public default constructor with no- argument constructor ONLY when none is provided, so every class has a constructor. 4.C# requires a constructor for every class 5.Constructors can also take arguments 6.Constructor header similar to regular method header except the name is always the class name

47 Jozef Goetz, 2015 46  When you declare a class, you can provide your own constructor to specify custom initialization: GradeBook myGradeBook = new GradeBook( "CS101 Introduction to C# Programming" );  "CS101 Introduction to C# Programming" is passed to the constructor. 4.10 Initializing Objects with Constructors

48 Jozef Goetz, 2015 47 Outline  GradeBook.cs  (1 of 2) Constructor to initialize courseName variable

49 Jozef Goetz, 2015 48 Outline  GradeBookTest.cs

50 Jozef Goetz, 2015 49 Fig. 4.16 | UML class diagram indicating that class GradeBook has a constructor with a name parameter of type string.  UML class diagram Constructors go in third compartment Place “ >” before constructor name and its arguments By convention, place constructors first in their compartment

51 Jozef Goetz, 2015 50 Error-Prevention Tip 4.1  provide a constructor to ensure that your class’s instance variables are properly initialized with meaningful values when each new object of your class is created.

52 Jozef Goetz, 2015 51 4.11 Floating-Point Numbers and Type decimal Floating-point numbers (Approximations)  Types float and double are called floating-point types. C# treats all real numbers you type in an application’s source code (such as 7.33 and 0.0975 ) as double values. Real #s also arise as a result of division. In conventional arithmetic, e.g. divide 10 by 3, the result is 3.333333…, with the sequence of 3s repeating infinitely (in binary 1010/11 = 11.010101…)  The computer allocates only a fixed amount of space to hold such a value, so clearly the stored floating-point value can be only an approximation – is not always 100% precise.

53 Jozef Goetz, 2015 52 4.11 Floating-Point Numbers and Type decimal p. 953  Floating-point numbers (Approximations) float (Single-Precision) – 4 bytes  15-16 significant digits double (Double-Precision) - 8 bytes  17 significant digits  Stores numbers with greater magnitude and precision than float  Floating-point literals such as 8.42 and 0.6734 are treated as double values by default  Type decimal variables store a limited range of real numbers, but are more precise and better suited for monetary amounts.  decimal – 16 bytes 29 significant digits Stores a limited range of real numbers precisely  Good for monetary apps decimal literal: Must type “M” or “m” after number e.g. 102.34M

54 Jozef Goetz, 2015 53 Common Programming Error 4.3  Using floating-point numbers in a manner that assumes they are represented precisely can lead to logic errors.  Don’t compare floating point values for equality and inequality, test the absolute value of the difference  Due to the imprecise nature of floating- point numbers, type decimal is preferred over the floating-point types whenever the calculation need to be exact, as with monetary calculations.

55 Jozef Goetz, 2015 54 Outline  Account.cs Method Credit receives one parameter named amount that is added to the property Balance. UML class diagram indicating that class Account has a public Balance property of type decimal, a constructor and a method Credit.

56 Jozef Goetz, 2015 55 Outline  AccountTest.cs  (1 of 2) Output: account1 balance: $50.00 account2 balance: $0.00 Enter deposit amount for account1: 49.99 adding $49.99 to account1 balance // Format specifier {0:C} - Used to //output monetary amount (currency) Passing an initial balance which will be invalidated by Balance ’s set accessor. Outputting the Balance property of each Account.

57 Jozef Goetz, 2015 56 Outline  AccountTest.cs  (2 of 2) Format specifier {0: C} - Used to output monetary amount (currency) Outputting the balances of both account s.

58 Jozef Goetz, 2015 57 Fig. 4.17 | string format specifiers.

59 Jozef Goetz, 2015 58 Error-Prevention Tip 4.2  The benefits of data integrity are not automatic simply because instance variables are made private —you must provide appropriate validity checking and report the errors.

60 Jozef Goetz, 2015 59 Error-Prevention Tip 4.3  set accessors that set the values of private data should verify that the intended new values are proper;  if they are not, the set accessors should leave the instance variables unchanged and generate an error.  We demonstrate how to gracefully generate errors in Chapter 13, Exception Handling.


Download ppt "Jozef Goetz, 2015 1  2014 Pearson Education, Inc. All rights reserved.  2002 Prentice Hall. All rights reserved. expanded by J. Goetz, 2015 credits:"

Similar presentations


Ads by Google