Anda di halaman 1dari 28

OOP

Objectives

“Classes, objects and object-oriented programming (OOP) play a


fundamental role in .NET. C# features full support for the object-
oriented programming paradigm…”

• Creating you own classes


• Class design

Microsoft 2
Part 1

• Creating your own classes…

Microsoft 3
Motivation

• .NET contains thousands of prebuilt classes in the FCL


• So why design your own?
– to model entities unique to your application domain…

• Examples:
– employees
– customers
– products
– orders
– documents
– business units
– etc.

Microsoft 4
Standard class members

• C# supports standard notion of fields and methods


• Example:
– employee class with name and salary

public class Employee


{
public string FirstName; // fields
public string LastName;
public decimal Salary;

public string GetSalary() // method to return formatted salary info


{
return this.Salary.ToString("$#,##0.00");
}

}//class

Microsoft 5
Who is "this"?

• The keyword this refers to the object executing the method

Employee emp; employee


emp = new Employee();
.
.
.
MessageBox.Show( emp.GetSalary() );

public class Employee


{
.
.
.
public string GetSalary()
{
return this.Salary.ToString("$#,##0.00");
}

Microsoft 6
"this" is optional

• The use of the this keyword is optional:


legal w/o
"this."
public class Employee
{
.
.
.
public string GetSalary()
{
return Salary.ToString("$#,##0.00");
}

– I consider it good style to use "this." to reinforce notion of OOP

Microsoft 7
Creating objects

• Every object is an instance of a class…


– hence the term "instantiation"
– objects created using the new keyword
employee

Employee emp1, emp2;

emp1 = new Employee(); // create new instance…


emp1.FirstName = "jim"; // initialize fields
emp1.LastName = "bag";
employee
emp1.Salary = 48900.01M;

emp2 = new Employee();


emp2.FirstName = "jane";
...

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

• "Classes should override ToString() and Equals()"

– so that classes behave properly within .NET…


– we've seen this already

Microsoft 11
Design rule #2

• "Object's data should be properly initialized"

Microsoft 12
Problem: object initialization

• How can we ensure that our objects are properly initialized?


– in particular, that fields have reasonable values

• Example:
– what if class user forgets to set employee's salary?

Employee emp;

emp = new Employee();


MessageBox.Show( emp.GetSalary() ); // what value is output?

Microsoft 13
Solution

• Constructors!
– special methods automatically called by new operator
– allowed to provide multiple constructors (overloading)

public class Employee


{
public string FirstName;
public string LastName;
public decimal Salary;

public Employee() // default constructor


{ … }

public Employee(string fn, string ln, decimal salary)


{ … } // parameterized constructor

Microsoft 14
Example

• Good class design often drops default constructor…

public class Employee


{
public string FirstName;
public string LastName;
public decimal Salary;

public Employee(string fn, string ln)


:this(fn, ln, 0.0M)
{ } // parameterized constructor with default salary, forwarding call to below

public Employee(string fn, string ln, decimal salary)


{
this.FirstName = fn;
this.LastName = ln;
this.Salary = salary;
}

Microsoft 15
Example (cont'd)

• … so class user is required to provide initial values:

Employee emp; X
emp = new Employee(); // COMPILER ERROR!
MessageBox.Show( emp.GetSalary() );


Employee emp;

emp = new Employee("jim", "bag", 48900.01M);


MessageBox.Show( emp.GetSalary() );

Microsoft 16
Design rule #3

• "Object's data should be properly cleaned up"

Microsoft 17
Problem: object finalization

• Are we notified when an object is being destroyed?


• Yes, but…
– unpredictable when notification will occur
– expensive to utilize

public class Employee


{
.
.
.

~Employee() // finalizer is called by GC just before object destroyed


{
...
}

Microsoft 18
Solution

• Don't rely upon execution of finalizer

• Either:
– redesign class so that finalization is unnecessary
– provide Close() or Dispose() methods for class users to call

Microsoft 19
Design rule #4

• "Hide as much as you can, and control access if not"

Microsoft 20
Problem: access control

• Sometimes, we want to control access to data…

• Example:
– suppose employee's IRA contribution is tied directly to salary (7%)
– what if class user changes salary but forgets IRA contribution?

public class Employee


{
public string FirstName;
public string LastName;
public decimal Salary;
public decimal IRAContr;
Employee emp;

emp = new Employee("jane", "doe", 58900.01M)


emp.Salary = emp.Salary + 1000.00M;

Microsoft 21
Solution #1

• Data hiding + accessor/mutator methods


– i.e. prevent class user from directly accessing data…

public class Employee


{
.
.
.
private decimal m_Salary, m_IRAContr; accesso
r
public decimal GetSalary()
{
return this.m_Salary;
}
mutato
public void SetSalary(decimal value) r
{
this.m_Salary = value;
this.m_IRAContr = value * 0.07M;
}

Microsoft 22
Solution #2

• Properties!
– a new kind of class member

• The ease of use of fields for our class users


• The benefits of methods for class developers
– i.e. controlled access to data

Microsoft 23
Properties

• Goal:
– to allow our class users to safely write code like this:

Employee emp;

emp = new Employee("jane", "doe", 58900.01M);


emp.Salary = emp.Salary + 1000.00M;

– provides field-like access with method-like semantics…


– … enabling access control, validation, data persistence,
screen updating, etc.

Microsoft 24
Observation

• Read of value ("Get") vs. Write of value ("Set")

Employee emp;

emp = new Employee("jane", "doe", 58900.01M);


emp.Salary = emp.Salary + 1000.00M;

Get
salary
Set
salary

Microsoft 25
Property implementation

• Implemented via get and set blocks…

public class Employee


{
.
.
.
private decimal m_Salary, m_IRAContr;

public decimal Salary


{
get { return this.m_Salary; }
set { this.m_Salary = value;
this.m_IRAContr = value * 0.07M; }
}

– the value keyword denotes the new value to set

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…

public class Employee


{
.
.
.
public decimal Salary
{
get { return this.m_Salary; }
set { this.m_Salary = value; }
}

public decimal IRAContribution


{
get { return this.m_Salary * 0.07M; }
}

Microsoft 27
Summary

• Object-oriented programming is *the* paradigm of .NET


• C# is a fully object-oriented programming language:
– fields
– methods
– constructors
– properties
– garbage collection

• Good class design is non-trivial…

Microsoft 28

Anda mungkin juga menyukai