creating your own classes -...

56
C# Programming: From Problem Analysis to Program Design 1 Creating Your Own Classes C# Programming: From Problem Analysis to Program Design 4th Edition 4

Upload: vankhuong

Post on 02-May-2018

224 views

Category:

Documents


4 download

TRANSCRIPT

C# Programming: From Problem Analysis to Program Design

1

Creating Your

Own Classes

C# Programming: From Problem Analysis to Program Design

4th Edition

4

C# Programming: From Problem Analysis to Program Design

2

Chapter Objectives

3

The Object Concept

Example1 – A Classical View of a Class Diagram

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 …

→ This style is commonly used

by Java and C++ developers.

Example2 – C# Class Diagrams: Geometric Figures

Example3 – University Seminar - Class Diagram

6

Note:

This UML Class Diagram shows multiple cooperative

classes as well as the associations (links) between them.

Example4 – An Inventory System - Class Diagram

7

Example5 – A Library System

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.

Writing Your Own Classes

10

Making a Class - Private Member Data

11

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; . . . }

C# Implementation of Private Member Data

(continued)

All data member

names should be

entered using

Camel-Notation.

Their corresponding

property names

should use Pascal-

Notation (later)

How to Create a Class using VS?

DRAWING THE CLASS

13

Class Diagram

14

Open the Class Diagram

from Solution Explorer

(right-click) View Class

Diagram

Private member variables

Public Properties (accessors)

User –Defined Methods

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.

Class Diagram (continued)

15

Right click on

class diagram to

open Class

Details window

Class Diagram (continued)

16

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

Creating Objects from Classes

17

Student s1 = new Student("1000", "Daenerys", "Targaryen", 99, 100, 100, "Political Sc."); Student s2 = new Student("1000", "Lannister", "Cersei", 50, 55, 65, "Social Services");

• new

null

Parts of a class: Constructors

18

Constructor (you need to type in this code)

public

19

//Default constructor - ZERO ARGUMENTS CONST. public Student() { studentNumber = "9999999"; 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)

Constructor (continued)

//Constructor with three parameters (optional)

public Student (string idValue, string firstValue, string lastValue)

{

studentNumber = idValue;

studentFirstName = firstValue;

studentLastName = lastValue;

}

20

Moving Data In/Out of Class

21

Student

Data

Methods

Value

22

Accessors – Classic Style (Java, C++, etc.)

public double GetStudentNumber( )

{

return studentNumber;

}

Get

Accessor

Student

Data

Methods

public void SetScore1( int gradeValue)

{

if (gradeValue < 0)

{

//convert negative grades to zero

gradeValue = 0;

}

score1 = gradeValue;

}

23

Accessors – Classic Style (Java, C++, etc.)

value Student

Data

Methods

24

public double SetNoOfSqYards(double squareYards)

{

noOfSquareYards = squareYards;

}

public void SetNoOfSquareYards(double length, double width)

{

noOfSquareYards = length * width;

}

Mutator

Accessors – Classic Style (Java, C++, etc.)

Accessors could be overridden

Overloaded

User-defined Methods

public double CalculateAverage( )

{

return (score1 + score2 + score3) / 3.0;

}

25

26

Using C# Property

C# Property

27

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.

Property (continued)

value

s1

s1.Score1 = 100;

value Score1.

28

29

ToString( ) Method

– 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

ToString()

• ToString()

– Write() – WriteLine()

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

Example - ToString( )

31

public override string ToString() { string niceOutput = "Student [" + " No: " + StudentNumber + " First: " + StudentFirstName + " Last: " + StudentLastName + " Score1: " + Score1 + " Score2: " + Score2 + " Score3: " + Score3 + " Major: " + Major + "]"; return niceOutput; }

32

Calling Instance Methods

object.method(args)

CalculateAverage()finalGrade = s1.CalculateAverage();

Math

Console ClassName.method(args)

answer = Math.Pow(4, 2);

Console.WriteLine("hello");

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

33

Calling the Constructor Method

C# Programming: From Problem Analysis to Program Design

34

Figure 4-4 Intellisense displays available constructors

Using Public Members

35 Figure 4-5 Public members of the Student class

StudentApp

C# Programming: From Problem Analysis to Program Design

36

Review StudentApp Project

Figure 4-6 Output from

StudentApp

Test Class

37

Testing Your New Class

38

Review CarpetCalculator Project

Figure 4-7 Output from

Carpet example using

instance methods

Example - English Distance Class

39

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;

}

} 40

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;

}

41

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;

}

}

}

42

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();

}

} 43

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

C# Programming: From Problem Analysis to Program Design

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 4-10 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

Figure 4-11 Structured

English for the

RealEstateInvestment

example

RealEstateInvestment

Example (continued)

Class Diagram

C# Programming: From Problem Analysis to Program Design

51

Figure 4-12 RealEstateInvestment class diagram

Test and Debug

C# Programming: From Problem Analysis to Program Design

52

Figure 4-13 Output from RealEstate Investment example

View RealEstateInvestment

Coding Standards

• Naming Conventions

– Classes

– Properties

– Methods

• Constructor Guidelines

• Spacing Guidelines

C# Programming: From Problem Analysis to Program Design

53

Resources

C# Programming: From Problem Analysis to Program Design

54

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