Beruflich Dokumente
Kultur Dokumente
Objectives
Microsoft 2
Part 1
Microsoft 3
Motivation
• Examples:
– employees
– customers
– products
– orders
– documents
– business units
– etc.
Microsoft 4
Standard class members
}//class
Microsoft 5
Who is "this"?
Microsoft 6
"this" is optional
Microsoft 7
Creating objects
Microsoft 8
Destroying objects
• You don't!
• Objects are never explicitly destroyed by the programmer
– .NET relies upon garbage collection to destroy objects
– garbage collector runs unpredictably…
Microsoft 9
Part 2
• Class design…
Microsoft 10
Design rule #1
Microsoft 11
Design rule #2
Microsoft 12
Problem: object initialization
• Example:
– what if class user forgets to set employee's salary?
Employee emp;
Microsoft 13
Solution
• Constructors!
– special methods automatically called by new operator
– allowed to provide multiple constructors (overloading)
Microsoft 14
Example
Microsoft 15
Example (cont'd)
Employee emp; X
emp = new Employee(); // COMPILER ERROR!
MessageBox.Show( emp.GetSalary() );
√
Employee emp;
Microsoft 16
Design rule #3
Microsoft 17
Problem: object finalization
Microsoft 18
Solution
• Either:
– redesign class so that finalization is unnecessary
– provide Close() or Dispose() methods for class users to call
Microsoft 19
Design rule #4
Microsoft 20
Problem: access control
• Example:
– suppose employee's IRA contribution is tied directly to salary (7%)
– what if class user changes salary but forgets IRA contribution?
Microsoft 21
Solution #1
Microsoft 22
Solution #2
• Properties!
– a new kind of class member
Microsoft 23
Properties
• Goal:
– to allow our class users to safely write code like this:
Employee emp;
Microsoft 24
Observation
Employee emp;
Get
salary
Set
salary
Microsoft 25
Property implementation
Microsoft 26
Read-only & Write-only properties
• Example:
– IRA contribution should be read-only, since tied to salary
– just delete the set block in this case…
Microsoft 27
Summary
Microsoft 28