Download presentation
Presentation is loading. Please wait.
1
Creating Your Own Classes
4 C# Programming: From Problem Analysis to Program Design 4th Edition C# Programming: From Problem Analysis to Program Design
2
Chapter Objectives Become familiar with the components of a class
Learn about the different methods and properties used for object-oriented development Create and use constructors Write your own instance methods to include mutators and accessors Call instance methods including mutators and accessors Work through a programming example that illustrates the chapter’s concepts C# Programming: From Problem Analysis to Program Design
3
The Object Concept Solutions are defined in terms of a collection of cooperating objects Class serves as template from which many objects can be created Abstraction Identify real-world entities and represent them as classes. For each class indicate Attributes (data) Behaviors (processes on the data)
4
Example1 – A Classical View of a Class Diagram
Graphical key Style1. The 'classical' class representation is not tied to any specific programming language. Instead, it is based on the Unified Modeling Language (UML) It emphasizes visibility of data and behavior. PERSON Attributes - personName : string - personAge : int Constructor(s) + Person() + Person(string nameValue, int ageValue) Accessors / Mutators + GetPersonName() : string + SetPersonName(string nameValue) + GetPersonAge() : int + SetPersonAge(int ageValue) User-Defined Methods + ToString() : string … other methods here … Data Behavior Person class → This style is commonly used by Java and C++ developers.
5
Example2 – C# Class Diagrams: Geometric Figures
Style 2. The C#-styled depiction of a class emphasizes the class - Fields (usually private), - Properties (field accessors), - and Methods.
6
Example3 – University Seminar - Class Diagram
Note: This UML Class Diagram shows multiple cooperative classes as well as the associations (links) between them.
7
Example4 – An Inventory System - Class Diagram
8
Example5 – A Library System
9
Example6 – Class Inheritance
This diagram shows the super-class Person and two descendant classes Student and Faculty, that generalize the ancestor class. We will study Inheritance in chapter 11.
10
Writing Your Own Classes
Implicit "contractual obligations" of a C# software developer to be followed when creating a class. Provide: Properties (in VS use propf hot-key combination, it combines a private data member, and its associated get/set accessors). Constructors (at least the Zero-Args and All-Args version). User-defined methods to perform behaviors of the class. Always include a version of the ToString() method.
11
Making a Class - Private Member Data
Observations Begin by identifying the class data members. When you define a class, you declare instance variables or fields that represent states of an object. Fields become visible to the component of the defining class, including all of its methods. Private fields cannot be seen outside of the class in which they are defined. Public fields are visible inside and outside the class, this is a DANGEROUS PRACTICE! Data members are almost always defined to have private access. All code you write is placed in a class (and saved in a separate file). Graphical key
12
C# Implementation of Private Member Data (continued)
public class Student { //Data members (data fields, or characteristics) private string studentNumber; private string studentLastName; private string studentFirstName; private int score1; private int score2; private int score3; private string major; . . . } All data member names should be entered using Camel-Notation. Their corresponding property names should use Pascal-Notation (later)
13
How to Create a Class using VS?
There are two options for adding a new class to a C# project. After you create the new class, you could either - Type-in its code, or - 'Draw' it using the Class Diagram Tool. DRAWING THE CLASS Use the top PROJECT menu or the Solution Explorer Window On 'Solution Explorer', point to the app's namespace entry. Right-click the entry. On the pop-up window select the option Add > New item > Class.cs Enter a name for the new item. Text editor opens showing the skeleton of the new class. On the Solution Explorer panel, point to the new class. Right-Click it. On the pop-up window choose 'View Class Diagram'
14
Figure 4-1 Student class diagram created in Visual Studio
Open the Class Diagram from Solution Explorer (right-click) View Class Diagram Private member variables → In VS2017 you need to install the graphic design tool. Go to menu Tools-> Get Tools and Features. Pick 'Visual Studio extension development' workload, choose 'Class Designer' option. Install. Public Properties (accessors) → User –Defined Methods → Figure 4-1 Student class diagram created in Visual Studio
15
Class Diagram (continued)
After the class diagram is created, add the names of data members or fields and methods using the Class Details section Right click on class diagram to open Class Details window Figure 4-2 Student class diagram details
16
Class Diagram (continued)
When you complete 'drawing' the Student class using the Class Diagram tool, its corresponding code is automatically placed in the file Student.cs Figure 4-3 Skeleton of auto generated code made for the Student class diagram
17
Creating Objects from Classes
Classes are blueprints from which objects are made or instantiated. Assume the Student class has been defined already. We may create two object s1 and s2 representing two different students as follows. Student s1 = new Student("1000", "Daenerys", "Targaryen", 99, 100, 100, "Political Sc."); Student s2 = new Student("1000", "Lannister", "Cersei", , 55, 65, "Social Services"); The keyword new is used to call the constructor that best fits the type and number of parameters passed in the invocation. If the object is created the system returns a reference to the it, otherwise it send back the value null.
18
Parts of a class: Constructors
Special type of method used to create objects Create instances of class Instantiate the class Constructors differ from other methods Constructors do not return a value, neither they include the void keyword void. Constructors use same identifier (name) as class Constructors use public access modifiers
19
Constructor (you need to type in this code)
Constructors are always given public access. //Default constructor - ZERO ARGUMENTS CONST. public Student() { studentNumber = " "; studentLastName = "n.a."; studentFirstName = "n.a."; score1 = 0; score2 = 0; score3 = 0; major = "Not declared yet"; } //Constructor with six arguments - ALL AGRGUMENTS CONST. public Student(string numberValue, string lastNameValue, string firstNameValue, int s1Value, int s2Value, int s3Value, string majorValue) studentNumber = numberValue; studentLastName = lastNameValue; studentFirstName = firstNameValue; score1 = s1Value; score2 = s2Value; score3 = s3Value; major = majorValue; (must) (must)
20
Constructor (continued)
//Constructor with three parameters (optional) public Student (string idValue, string firstValue, string lastValue) { studentNumber = idValue; studentFirstName = firstValue; studentLastName = lastValue; } Conventions regarding constructors Constructors should be the ONLY class methods that directly access the private data members. All other methods should use the class Properties (explained later). A good programming practice is to always include the Zero-arguments and the All-arguments constructors.
21
Moving Data In/Out of Class
There are two C# strategies used to safely introduce and retrieve data into/from a private data member Use Get – Set accessors (Typical of Java, C++) Use Properties (unique to C#) Student Data Methods Get methods 'extract' data from the class Set methods 'carry' data into the class Value Traditional approach to data traffic control in a class
22
Accessors – Classic Style (Java, C++, etc.)
Getter Method Returns the current value of a private data member. Standard naming convention, for each private data member create a method prefixed with “Get”, use Pascal-Notation (e.g. GetMajor() ) Example. Accessor for the private member studentNumber public double GetStudentNumber( ) { return studentNumber; } Get Accessor Student Data Methods Get methods 'extract' data from the class
23
Accessors – Classic Style (Java, C++, etc.)
Setter Methods (Mutators) Normally include only one parameter. Here you may implement 'business rules' at the item level. For instance, scores must be positive, age less than a120, etc. Standard naming convention → prefix with ”Set”, use Pascal notation Example. Consider the Student class. Assign a grade to score1. public void SetScore1( int gradeValue) { if (gradeValue < 0) //convert negative grades to zero gradeValue = 0; } score1 = gradeValue; Student Data Methods Set methods 'carry' data into the class value
24
Accessors – Classic Style (Java, C++, etc.)
public double SetNoOfSqYards(double squareYards) { noOfSquareYards = squareYards; } public void SetNoOfSquareYards(double length, double width) noOfSquareYards = length * width; Mutator Overloaded Accessors could be overridden
25
User-defined Methods User-defined methods
Declared in the same class as the data members Instance methods can directly access private data members Not meant to be used for data exchange; instead typically used for calculating a value using private data members public double CalculateAverage( ) { return (score1 + score2 + score3) / 3.0; }
26
Using C# Property This is the recommended Approach
Can replace accessors and mutators. They 'fuse' together a private data member with their get- set accessors. Properties looks like a public data field (but they are not!) Standard naming convention in C# for properties Use the same name as the instance variable or field, but start with uppercase character. For example, if private data member is studentMajor its property should be StudentMajor.
27
C# Property class Student { //private data members ... private int score1; //Properties public int Score1 get { return score1; } set //convert incoming negative grades to zero if (value < 0) value = 0; } score1 = value; //...rest of the class goes here ... value is a special C# variable used as general alias for input data arriving to a property.
28
Property (continued) What is the meaning of value used by properties?
Assume we have created an object s1 representing an instance of the Student class. Assigning a grade to her first test could be done as follows s1.Score1 = 100; Here, 100 is the value supplied to the property Score1.
29
ToString( ) Method All classes inherit four methods from the super Object class ToString() //show yourself! Equals() //are you equal to this other object? GetType() //tell what type of data item you are GetHashCode() //tell your unique identifier code Use ToString() to produce a 'nice looking' display of the object, telling all of its data. ToString() method is called automatically by several methods Write() WriteLine() The following statements are equivalent Console.WriteLine(s1); Console.WriteLine(s1.ToString());
30
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 It is understood that we must always override the ToString() method. This enables us to decide what should be displayed if the object is printed
31
Example - ToString( ) Consider the Student class.
public override string ToString() { string niceOutput = "Student [" + " No: " + StudentNumber + " First: " + StudentFirstName + " Last: " + StudentLastName + " Score1: " + Score1 + " Score2: " + Score2 + " Score3: " + Score3 + " Major: " + Major + "]"; return niceOutput; } If the method is NOT overridden the object would be displayed as it appears on the right
32
Calling Instance Methods
Instance methods are generally nonstatic. They must be called with objects – not classes. The syntax for the invocation is object.method(args) Assume object s1 is an instance of the Student class. You may call the non-static CalculateAverage() method as follows: finalGrade = s1.CalculateAverage(); As a counter example, static calls to members of Math and Console classes uses syntax ClassName.method(args) answer = Math.Pow(4, 2); Console.WriteLine("hello"); If you need to invoke a method inside the class in which it is defined, simply use the method's name (no qualifier needed).
33
Testing Your New Class A different class is needed for testing and using your class Test class has Main( ) in it Construct objects of your class Use the properties to assign and retrieve values Invoke instance methods using the objects you construct C# Programming: From Problem Analysis to Program Design
34
Calling the Constructor Method
Figure 4-4 Intellisense displays available constructors C# Programming: From Problem Analysis to Program Design
35
Using Public Members Discovering public Properties (wrench icon) and Methods (purple box icon) exposed by the VisualStudio IDE. Type object's name followed by a dot. Intellisense responds with a panel listing available components. Figure 4-5 Public members of the Student class
36
StudentApp Figure 4-6 Output from StudentApp Review StudentApp Project
C# Programming: From Problem Analysis to Program Design
37
Test Class With multiclass solutions all input and output should be included in the class that has the Main( ) method Eventual goal will be to place your class files, like Student and CarpetCalculator, in a library so that the classes can be used by different applications Some of these applications might be Windows applications; some may be console applications; others may be Web application Do not include ReadLine( ) or WriteLine( ) in your class methods
38
Testing Your New Class Review CarpetCalculator Project
Figure 4-7 Output from Carpet example using instance methods Review CarpetCalculator Project
39
Example - English Distance Class
Problem Implement a class representing distances (feet and inches) using the Imperial English Distance model. Inches value must be normalized (cannot be greater than 12) Provide a method to convert distance to meters.
40
Example - English Distance Class 1 of 4
class EDistance { //OK to make constant publicly available (prefix EDistance.) public const double INCHES_TO_CM = 2.54; //properties & private members private int feet; private int inches; public int Inches get { return inches; } set //correct inches in case they are > 12 feet += value / 12; inches = value % 12; }
41
Example - English Distance Class 2 of 4
public int Feet { get { return feet; } set { feet = value; } } //constructor(s) public EDistance() //Observe, we use properties, not the priv. vars. Feet = 0; Inches = 0; public EDistance(int feetValue, int inchesValue) //Style: add postFix Value to each incoming argument Feet = feetValue; Inches = inchesValue;
42
Example - English Distance Class 3 of 4
//user-defined methods public override string ToString() { return string.Format("Edistance [ {0}\' {1}\" ]", Feet, Inches); } public double ToMeters() double cm = (12 * Feet + Inches) * INCHES_TO_CM; return cm / 100;
43
Example - English Distance Class 4 of 4
//Testing the EDistance class class Program { static void Main(string[] args) //call the all-arguments constructor EDistance ed1 = new EDistance(6, 2); Console.WriteLine(ed1); Console.WriteLine(ed1.ToMeters()); //call the zero-arguments constructor EDistance ed2 = new EDistance(); ed2.Feet = 3; ed2.Inches = 14; Console.WriteLine(ed2); Console.Read(); }
44
RealEstateInvestment Example
Figure 4-8 Problem specification for RealEstateInvestment example
45
Data for the RealEstateInvestment Example
Table 4-2 Instance variables for the RealEstateInvestment class
46
Data for the RealEstateInvestment Example (continued)
Table 4-3 local variables for the property application class C# Programming: From Problem Analysis to Program Design
47
RealEstateInvestment Example (continued)
Figure 4-9 Prototype C# Programming: From Problem Analysis to Program Design
48
RealEstateInvestment Example (continued)
Figure Class diagrams C# Programming: From Problem Analysis to Program Design
49
RealEstateInvestment Example (continued)
Table 4-4 Properties for the RealEstateInvestment class C# Programming: From Problem Analysis to Program Design
50
RealEstateInvestment Example (continued)
Figure Structured English for the RealEstateInvestment example C# Programming: From Problem Analysis to Program Design
51
Class Diagram Figure 4-12 RealEstateInvestment class diagram
C# Programming: From Problem Analysis to Program Design
52
View RealEstateInvestment
Test and Debug Figure Output from RealEstate Investment example View RealEstateInvestment C# Programming: From Problem Analysis to Program Design
53
Coding Standards Naming Conventions Constructor Guidelines
Classes Properties Methods Constructor Guidelines Spacing Guidelines C# Programming: From Problem Analysis to Program Design
54
Resources C# Coding Standards and Best Practices –
C# Station Tutorial - Introduction to Classes – Object-Oriented Programming – Introduction to Objects and Classes in C# C# Programming: From Problem Analysis to Program Design
55
Chapter Summary Components of a method:
modifiers + returnType + methodName + parameters + body Class methods Parameters: value, ref, out, default values Predefined methods (ToString, Equals,…) Value- and nonvalue-returning methods C# Programming: From Problem Analysis to Program Design
56
Chapter Summary (continued)
Properties Instance methods Constructors Mutators / Accessors User-defined methods Types of parameters C# Programming: From Problem Analysis to Program Design
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.