1 / 50

C# Classes in Depth Version 1.1

C# Classes in Depth Version 1.1. Topics. Designing Your Own Classes Attributes, Behaviors & Properties C# Class Definitions Creating and Using Objects. Objectives. At the completion of this topic, students should be able to:. Design classes for use in a C# program

denton
Download Presentation

C# Classes in Depth Version 1.1

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. C# Classes in DepthVersion 1.1

  2. Topics Designing Your Own Classes Attributes, Behaviors & Properties C# Class Definitions Creating and Using Objects

  3. Objectives At the completion of this topic, students should be able to: Design classes for use in a C# program Explain the difference between a class and an object Explain what attributes, behaviors & properties are Explain the terms encapsulation and data hiding Create a program that uses a programmer designed class

  4. Objects are used to model real-world things. Let’s consider an object that represents a time.

  5. Real world objects have attributes An object’s attributes describe its “state of being” What things do we normally associate with the state of a time? minutes seconds am/pm hours

  6. An object also has behaviors behaviors define how you interact with the object What can you do with a time? set a time display a time format a time

  7. An object also has properties properties look like attributes, act like attributes, but are really behaviors with getters/setters. What can you do with a time via properties? set a time display a time format a time

  8. An Object’s Attributes, Behaviors & Properties Should Work Together this is called cohesion

  9. A instance Class is a blueprint that a program uses when it creates an object. A instance class reserves no space in memory When an object is created from and instance class blueprint, memory is reserved to hold the object’s attributes. An object is known as an instance of the class. Each object has it’s own space and data.

  10. A class is said to be an abstraction of the real world object that we are modeling.

  11. Encapsulation Time object DisplayTime( ) member methods & properties are declared as public calling method we should not allow code outside of the object to reach in and change the data directly. Instead, we call methods in the object to do it for us. hour minute second member data is declared as private public and private are called access modifiers

  12. We use a UML Class Diagram to document the data and methods contained in our class.

  13. A UML class diagramis used to describe a class in a very precise way. A class diagram is a rectangle. At the top of the rectangle is the class name. A line separates the class name from the rest of the diagram. Time public class Time { } code represented by the UML diagram

  14. Time Following the class name we write the data members of the class. A line separates the data members from the rest of the diagram. - hour: int access modifier: + public - private public class Time { private int hour; } Code represented by the UML diagram data member name data type

  15. Time Following the class name we write the data members of the class. A line separates the data members from the rest of the diagram. • hour: int • minute: int • second: int public class Time { private int hour; private int minute; private int second; } Code represented by the UML diagram

  16. Time Following the data members, we write the member methods. • hour: int • minute: int • second: int public class Time { private int hour; private int minute; private int second; public void DisplayTime( ) { }; } Code represented by the UML diagram + DisplayTime( ): void access modifier + public - private method name return type parameters

  17. Time Following the data members, we write the member methods. • hour: int • minute: int • second: int public class Time { private int hour; private int minute; private int second; public void DisplayTime( ) { }; public void SetTime(int, int, int) { }; } Code represented by the UML diagram + DisplayTime( ): void + SetTime(:int, :int, :int):void

  18. It is important that class diagrams be drawn precisely and that they conform to the form shown in these examples.

  19. To start a class definition The class name we have chosen The keyword “class” The keyword public public class Time { } A set of curly braces … The body of the class will go in between them.

  20. Declaring Member Data Member data is always “private” public class Time { private int hour; } Indent each line inside the block variable name data type

  21. Declaring Member Data public class Time { private int hour; } We call data members of a class “Instance Data” because each instance (object) of the class will contain its own unique copy of this data.

  22. Declaring Member Data public class Time { private int hour; private int minute; private int second; }

  23. Declaring Member Methods public class Time { private int hour; private int minute; private int second; public void SetTime( int hr, int min, int sec) { } } Member methods are usually public parameters method name return type

  24. Declaring Member Methods public class Time { private int hour; private int minute; private int second; public void SetTime( int hr, int min, int sec) { } } The body of the method goes between these curly braces

  25. Don’t Forget the Method Prologue public class Time { private int hour; private int minute; private int second; public void SetTime( int hr, int min, int sec) { hour = hr; minute = min; second = second; } } // The SetTime method // Purpose: Set the time values // Parameters: an hour, minute and second value // Returns: none

  26. “Setter”Methods they are usually named “set” plus the name of the instance variable they will return the value of. public class Time { . . . public void SetHour(int hr) { hour = hr; } } setters never return anything setters always take a parameter

  27. “Getter”Methods they are usually named “get” plus the name of the instance variable they will return the value of. public class Time { . . . public intGetHour( ) { return hour; } } getters always return something getters take no parameters

  28. The methods public void SetTime(int, _hr, int _min, int _sec) public void DisplayTime( ) etc . . . are the public services or the public interface that this class offers to its clients. Clients are neither aware of nor involved in the implementation details of these methods. Clients care what a method does, but not how it does it.

  29. The data members (or fields) in the Time class private int hour; private int minute; private int second; are all declared as private. This hides the data from a client. Clients must use the public interface to access any data. This is known as information hiding. Getters and setters provide a controlled way for programmer’s to retrieve or modify the contents of a data member. These are provided as a property in the class.

  30. Properties C# provides an elegant way of accessing data members of a class by using properties. Properties contain code that handles the details of getting and/or setting the values of a data member. After defining a property you can use it just like a data member of the class in your code.

  31. Properties You have already see some properties in C# For example, the Length property of an array.

  32. Let’s replace the getters and setterswith properties. public class Time { // data members private int hour; . . . public int Hour { get { return hour; } set { if (value < 0 || value > 23) hour = value; else { Console.WriteLine(“Invalid hour value, hour was set to 1”); hour = 1; } }

  33. Get Accessor private int hour; . . . public int Hour { get { return hour; } set { if (value < 0 || value > 23) { Console.WriteLine("Invalid hour value, hour was set to 1"); hour = 1; } else hour = value; } } Note the difference in capitalization. The keyword “get” is called a property accessor. When a property is read, the get accessor code is executed. It must return a value of the property’s type.

  34. Set Accessor private int hour; . . . public int Hour { get { return hour; } set { if (value < 0 || value > 23) { Console.WriteLine("Invalid hour value, hour was set to 1"); hour = 1; } else hour = value; } } When a property is assigned, the set accessor code is executed. It provides complete control over the how the value of a property is set. value is the number assigned to the property.

  35. To Use a Property Time time1 = new Time( ); time1.Hour = 5; //set accessor called Console.WriteLine(time1.Hour); //get accessor called

  36. Why Should I Use Properties? Properties provide a simple controlled way of accessing private data. Suppose that in our Time class we decided to store a time as the number of seconds past midnight. Without changing the public interface, we could support time this way by altering the get and set accessors as shown:

  37. private int _secondsPastMidnight; const int _SECONDS_PER_MINUTE = 60; const int _MINUTES_PER_SECOND = 60; . . . public int Hour { get { return _secondsPastMidnight / _SECONDS_PER_MIN / _MINUTES_PER_HOUR; } set { if (value < 0 || value > 23) { Console.WriteLine("Invalid hour value, hour was set to 1"); _hour = _MINUTES_PER_HOUR * _SECONDS_PER_MINUTE; } else _hour = _value * _MINUTES_PER_HOUR * _SECONDS_PER_MINUTE } }

  38. Note that a Property is not a variable, and so you cannot pass a property by reference.

  39. Automatic Properties The most common implementation for a property is just a getter and a setter that reads and writes to a private data field in the class. The compiler will automatically create the associated data field when you write the property this way: public int Hour{get; set;}

  40. Read Only Properties A property is read only when it only has a get accessor and NO set accessor. It is possible to have a write only property (NO get accessor), but they are rarely used.

  41. Read Only Data Up until this point in time we have used constants to represent data that we don’t want to change inside of an application. The problem with a constant is that it is defined at compile time. What if we want to have a data member of a class that we want to treat as constant, but we want to be able to initialize this data member in the class constructor? To do this, use the readonly keyword … private readonlyint INCREMENT; The constructor can assign a value to INCREMENT . The data is not considered unchangeable until after the constructor completes execution.

  42. Static Data Every instance object has its own copy of all of the instance variables in a class. What if you want to have all objects of a class share a single instance of a variable? For example, all savingsAccount objects might have the same interest rate. To do this, declare the variable as private static double interestRate = 0.0725; static variables and methods have NO associated this variable

  43. The this reference Every instance object contains a variable named this, that is a reference to itself. The keyword is often used when you want to explicitly name a variable as a data member of this object. For example, in the Time class we have discussed is a method public void SetTime( int hr, int min, int sec) { hour = hr; minute = min; second = sec; }

  44. The this reference Using the this reference we could write: public void SetTime( int hr, int min, int sec) { this.hour = hr; this.minute = min; this.second = sec; }

  45. Creating Objects

  46. Class definition Time startTime = new Time( ); public class Time { private int hour; private int minute; private int second; . . . } this statement takes the Time class definition and uses it to create the object “startTime”. When creating the object, storage is allocated for the each of the data members defined in the class. Each data member is initialized to a standard default value. Hour Minute second startTime

  47. Sending Messages to Objects

  48. parameter startTime.SetHour(8) ); message . object name method name hour minute second startTime

  49. parameter startTime.SetHour(8) ); This statement send the SetHour message to the object named startTime. As the method executes, the value of the parameter hr is stored in the instance variable hour. message message hour minute second startTime void SetHour(int hr) { hour = hr; }

  50. Let’s Write The Code

More Related