görsel c # ile windows programlama güz 200 9 ( 7 . hafta)

59
2006 Pearson Education, Inc. All rights rese Görsel C# ile Windows Programlama Güz 2009 (7. Hafta)

Upload: ima-hess

Post on 02-Jan-2016

44 views

Category:

Documents


0 download

DESCRIPTION

Görsel C # ile Windows Programlama Güz 200 9 ( 7 . Hafta). Kompozisyon (Composition). B ir sınıf, üye değişkeni olarak başka sınıfların nesnelerini kullanıyorsa bu durum bir kompozisyondur. Kompozisyonlar çoğu zaman has-a-relationship olarak da nitelendirilirler. Date.cs (1 of 5). - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Görsel C #  ile Windows Programlama Güz  200 9 ( 7 . Hafta)

2006 Pearson Education, Inc. All rights reserved.

Görsel C# ile Windows Programlama

Güz 2009

(7. Hafta)

Page 2: Görsel C #  ile Windows Programlama Güz  200 9 ( 7 . Hafta)

2006 Pearson Education, Inc. All rights reserved.

2

Kompozisyon (Composition)

• Bir sınıf, üye değişkeni olarak başka sınıfların nesnelerini kullanıyorsa bu durum bir kompozisyondur.

• Kompozisyonlar çoğu zaman has-a-relationship olarak da nitelendirilirler.

Page 3: Görsel C #  ile Windows Programlama Güz  200 9 ( 7 . Hafta)

2006 Pearson Education, Inc. All rights reserved.

3 1 // Date.cs

2 // Date class declaration.

3 using System;

4

5 public class Date

6 {

7 private int month; // 1-12

8 private int day; // 1-31 based on month

9 private int year; // any year (could validate)

10

11 // constructor: use property Month to confirm proper value for month;

12 // use property Day to confirm proper value for day

13 public Date( int theMonth, int theDay, int theYear )

14 {

15 Month = theMonth; // validate month

16 Year = theYear; // could validate year

17 Day = theDay; // validate day

18 Console.WriteLine( "Date object constructor for date {0}", this );

19 } // end Date constructor

Date.cs

(1 of 5)

Page 4: Görsel C #  ile Windows Programlama Güz  200 9 ( 7 . Hafta)

2006 Pearson Education, Inc. All rights reserved.

420

21 // property that gets and sets the year

22 public int Year

23 {

24 get

25 {

26 return year;

27 } // end get

28 private set // make writing inaccessible outside the class

29 {

30 year = value; // could validate

31 } // end set

32 } // end property Year

Date.cs

(2 of 5)

Page 5: Görsel C #  ile Windows Programlama Güz  200 9 ( 7 . Hafta)

2006 Pearson Education, Inc. All rights reserved.

533

34 // property that gets and sets the month

35 public int Month

36 {

37 get

38 {

39 return month;

40 } // end get

41 private set // make writing inaccessible outside the class

42 {

43 if ( value > 0 && value <= 12 ) // validate month

44 month = value;

45 else // month is invalid

46 {

47 Console.WriteLine( "Invalid month ({0}) set to 1.", value );

48 month = 1; // maintain object in consistent state

49 } // end else

50 } // end set

51 } // end property Month

Date.cs

(3 of 5)

Validates month value

Page 6: Görsel C #  ile Windows Programlama Güz  200 9 ( 7 . Hafta)

2006 Pearson Education, Inc. All rights reserved.

652

53 // property that gets and sets the day

54 public int Day

55 {

56 get

57 {

58 return day;

59 } // end get

60 private set // make writing inaccessible outside the class

61 {

62 int[] daysPerMonth =

63 { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };

64

65 // check if day in range for month

66 if ( value > 0 && value <= daysPerMonth[ Month ] )

67 day = value;

68 // check for leap year

69 else if ( Month == 2 && value == 29 &&

70 ( Year % 400 == 0 || ( Year % 4 == 0 && Year % 100 != 0 ) ) )

71 day = value;

72 else

73 {

74 Console.WriteLine( "Invalid day ({0}) set to 1.", value );

75 day = 1; // maintain object in consistent state

76 } // end else

77 } // end set

78 } // end property Day

Date.cs

(4 of 5)

Validates day value

Page 7: Görsel C #  ile Windows Programlama Güz  200 9 ( 7 . Hafta)

2006 Pearson Education, Inc. All rights reserved.

779

80 // return a string of the form month/day/year

81 public override string ToString()

82 {

83 return string.Format( "{0}/{1}/{2}", Month, Day, Year );

84 } // end method ToString

85 } // end class Date

Date.cs

(5 of 5)

Page 8: Görsel C #  ile Windows Programlama Güz  200 9 ( 7 . Hafta)

2006 Pearson Education, Inc. All rights reserved.

8 1 // Employee.cs

2 // Employee class with references to other objects.

3 public class Employee

4 {

5 private string firstName;

6 private string lastName;

7 private Date birthDate;

8 private Date hireDate;

9

10 // constructor to initialize name, birth date and hire date

11 public Employee( string first, string last,

12 Date dateOfBirth, Date dateOfHire )

13 {

14 firstName = first;

15 lastName = last;

16 birthDate = dateOfBirth;

17 hireDate = dateOfHire;

18 } // end Employee constructor

19

20 // convert Employee to string format

21 public override string ToString()

22 {

23 return string.Format( "{0}, {1} Hired: {2} Birthday: {3}",

24 lastName, firstName, hireDate, birthDate );

25 } // end method ToString

26 } // end class Employee

Employee.cs

Employee contains references to two Date objects

Implicit calls to hireDate and birthDate’s ToString methods

Page 9: Görsel C #  ile Windows Programlama Güz  200 9 ( 7 . Hafta)

2006 Pearson Education, Inc. All rights reserved.

9 1 // EmployeeTest.cs

2 // Composition demonstration.

3 using System;

4

5 public class EmployeeTest

6 {

7 public static void Main( string[] args )

8 {

9 Date birth = new Date( 7, 24, 1949 );

10 Date hire = new Date( 3, 12, 1988 );

11 Employee employee = new Employee( "Bob", "Blue", birth, hire );

12

13 Console.WriteLine( employee );

14 } // end Main

15 } // end class EmployeeTest Date object constructor for date 7/24/1949 Date object constructor for date 3/12/1988 Blue, Bob Hired: 3/12/1988 Birthday: 7/24/1949

EmployeeTest.cs

Create an Employee object

Display the Employee object

Page 10: Görsel C #  ile Windows Programlama Güz  200 9 ( 7 . Hafta)

2006 Pearson Education, Inc. All rights reserved.

10

Garbage Collection ve Yıkıcılar (Destructors)

• Garbage Collection otomatik olarak belleği kontrol eden ve artık kullanımda olmayan nesnelerin işgal ettiği bellek alanlarının yeniden kullanılabilmesini sağlayan bir mekanizmadır.

• Nesneler bir daha ihtiyaç duyulmadıklarında yok edilirler. Bu işlemi yıkıcılar yani destructor lar dediğimiz yapılar garbage collector tarafından çağrılarak gerçekleştirirler. Yıkıcılar da yapıcılar (constructor) gibi sınıfın adıyla aynı olurlar. Yapıcılardan tek farkları sınıf adının önüne getirilen ~ işaretidir.

Page 11: Görsel C #  ile Windows Programlama Güz  200 9 ( 7 . Hafta)

2006 Pearson Education, Inc. All rights reserved.

11

Hatırlatma......

Bir sınıf kullandığı herhangi bir sistem kaynağını (diskten okuyup islem yaptığı bir dosya gibi) işi bittiği zaman serbest bırakmalıdır. Birçok FCL sınıfı bu amaçla Close veya Dispose metodlarını kullanır.

Page 12: Görsel C #  ile Windows Programlama Güz  200 9 ( 7 . Hafta)

2006 Pearson Education, Inc. All rights reserved.

12

static Üye Değişkenler

•static üye değişkenler bir sınıfın bütün nesnelerinin ortak kullandığı değişkenlerdir. static olmayan üye değişkenler hatırlanacağı üzere herbir nesne için farklı değerlere sahip olabiliyorlardı.

•static üye değişkenlere deklare edildiklerinde muhakkak bir ilk değer ataması yapılmalıdır. Aksi takdirde derleyicinin kendisi bir ilk değer ataması yapar. (Örneğin static bir int değişkenine sıfır değerini atar derleyici.)

Page 13: Görsel C #  ile Windows Programlama Güz  200 9 ( 7 . Hafta)

2006 Pearson Education, Inc. All rights reserved.

13 1 // Employee.cs

2 // Static variable used to maintain a count of the number of

3 // Employee objects in memory.

4 using System;

5

6 public class Employee

7 {

8 private string firstName;

9 private string lastName;

10 private static int count = 0; // number of objects in memory

11

12 // initialize employee, add 1 to static count and

13 // output string indicating that constructor was called

14 public Employee( string first, string last )

15 {

16 firstName = first;

17 lastName = last;

18 count++; // increment static count of employees

19 Console.WriteLine( "Employee constructor: {0} {1}; count = {2}",

20 FirstName, LastName, Count );

21 } // end Employee constructor

Employee.cs

(1 of 3)

Declare a static field

Increment static field

Page 14: Görsel C #  ile Windows Programlama Güz  200 9 ( 7 . Hafta)

2006 Pearson Education, Inc. All rights reserved.

1422

23 // subtract 1 from static count when the garbage collector

24 // calls destructor to clean up object;

25 // confirm that destructor was called

26 ~Employee()

27 {

28 count--; // decrement static count of employees

29 Console.WriteLine( "Employee destructor: {0} {1}; count = {2}",

30 FirstName, LastName, Count );

31 } // end destructor

32

33 // read-only property that gets the first name

34 public string FirstName

35 {

36 get

37 {

38 return firstName;

39 } // end get

40 } // end property FirstName

Employee.cs

(2 of 3)

Declare a destructor

Page 15: Görsel C #  ile Windows Programlama Güz  200 9 ( 7 . Hafta)

2006 Pearson Education, Inc. All rights reserved.

1541

42 // read-only property that gets the last name

43 public string LastName

44 {

45 get

46 {

47 return lastName;

48 } // end get

49 } // end property LastName

50

51 // read-only property that gets the employee count

52 public static int Count

53 {

54 get

55 {

56 return count;

57 } // end get

58 } // end property Count

59 } // end class Employee

Employee.cs

(3 of 3)

Declare static property Count to get static field count

Page 16: Görsel C #  ile Windows Programlama Güz  200 9 ( 7 . Hafta)

2006 Pearson Education, Inc. All rights reserved.

16 1 // EmployeeTest.cs

2 // Static member demonstration.

3 using System;

4

5 public class EmployeeTest

6 {

7 public static void Main( string[] args )

8 {

9 // show that count is 0 before creating Employees

10 Console.WriteLine( "Employees before instantiation: {0}",

11 Employee.Count );

12

13 // create two Employees; count should become 2

14 Employee e1 = new Employee( "Susan", "Baker" );

15 Employee e2 = new Employee( "Bob", "Blue" );

16

17 // show that count is 2 after creating two Employees

18 Console.WriteLine( "\nEmployees after instantiation: {0}",

19 Employee.Count );

EmployeeTest.cs

(1 of 3)

Create new Employee objects

Call static property Count using class name Employee

Page 17: Görsel C #  ile Windows Programlama Güz  200 9 ( 7 . Hafta)

2006 Pearson Education, Inc. All rights reserved.

1720

21 // get names of Employees

22 Console.WriteLine( "\nEmployee 1: {0} {1}\nEmployee 2: {2} {3}\n",

23 e1.FirstName, e1.LastName,

24 e2.FirstName, e2.LastName );

25

26 // in this example, there is only one reference to each Employee,

27 // so the following statements cause the CLR to mark each

28 // Employee object as being eligible for destruction

29 e1 = null; // object e1 no longer needed

30 e2 = null; // object e2 no longer needed

31

32 GC.Collect(); // ask for garbage collection to occur now

33 // wait until the destructors

34 // finish writing to the console

35 GC.WaitForPendingFinalizers();

36

37 // show Employee count after calling garbage collector and

38 // waiting for all destructors to finish

39 Console.WriteLine( "\nEmployees after destruction: {0}",

40 Employee.Count );

41 } // end Main

42 } // end class EmployeeTest

EmployeeTest.cs

(2 of 3)

Remove references to objects, CLR will mark them for garbage collection

Call static method Collect of class GC to indicate that garbage collection should be attempted

Call static property Count using class name Employee

Page 18: Görsel C #  ile Windows Programlama Güz  200 9 ( 7 . Hafta)

2006 Pearson Education, Inc. All rights reserved.

18

EmployeeTest.cs

(3 of 3)

Employees before instantiation: 0 Employee constructor: Susan Baker; count = 1

Employee constructor: Bob Blue; count = 2 Employees after instantiation: 2

Employee 1: Susan Baker Employee 2: Bob Blue

Employee destructor: Bob Blue; count = 1 Employee destructor: Susan Baker; count = 0

Employees after destruction: 0

Page 19: Görsel C #  ile Windows Programlama Güz  200 9 ( 7 . Hafta)

2006 Pearson Education, Inc. All rights reserved.

19

readonly Üye Değişkenler

•readonly üye değişkenlerin değerleri sonradan değiştirilemez. Bu değişkenlere ya deklare edildiklerinde bir ilk değer ataması yapılır ya da atama işlemi bir constructor içerisinde gerçekleştirilir.

Page 20: Görsel C #  ile Windows Programlama Güz  200 9 ( 7 . Hafta)

2006 Pearson Education, Inc. All rights reserved.

20 1 // Increment.cs

2 // readonly instance variable in a class.

3 public class Increment

4 {

5 // readonly instance variable (uninitialized)

6 private readonly int INCREMENT;

7 private int total = 0; // total of all increments

8

9 // constructor initializes readonly instance variable INCREMENT

10 public Increment( int incrementValue )

11 {

12 INCREMENT = incrementValue; // initialize readonly variable (once)

13 } // end Increment constructor

14

15 // add INCREMENT to total

16 public void AddIncrementToTotal()

17 {

18 total += INCREMENT;

19 } // end method AddIncrementToTotal

20

21 // return string representation of an Increment object's data

22 public override string ToString()

23 {

24 return string.Format( "total = {0}", total );

25 } // end method ToString

26 } // end class Increment

Increment.cs

Declare readonly instance variable

Initialize readonly instance variable inside a constructor

Page 21: Görsel C #  ile Windows Programlama Güz  200 9 ( 7 . Hafta)

2006 Pearson Education, Inc. All rights reserved.

21 1 // IncrementTest.cs

2 // readonly instance variable initialized with a constructor argument.

3 using System;

4

5 public class IncrementTest

6 {

7 public static void Main( string[] args )

8 {

9 Increment incrementer = new Increment( 5 );

10

11 Console.WriteLine( "Before incrementing: {0}\n", incrementer );

12

13 for ( int i = 1; i <= 3; i++ )

14 {

15 incrementer.AddIncrementToTotal();

16 Console.WriteLine( "After increment {0}: {1}", i, incrementer );

17 } // end for

18 } // end Main

19 } // end class IncrementTest Before incrementing: total = 0 After increment 1: total = 5 After increment 2: total = 10 After increment 3: total = 15

IncrementTest.cs

Create an Increment object

Call method AddIncrementToTotal

Page 22: Görsel C #  ile Windows Programlama Güz  200 9 ( 7 . Hafta)

2006 Pearson Education, Inc. All rights reserved.

22

Hatırlatma....

readonly tanımlanan üye değişkenleri sınıfın bütün nesnelerinde farklı kopya değerleri ile temsil edilirler. Eğer bütün nesneler için aynı sabit değere sahip bir üye değişken isteniyorsa bu durumda const kullanılmalıdır. const sanki dolaylı olarak tanımlanmış sabit bir statik değişken gibi değerlendirilir.

Page 23: Görsel C #  ile Windows Programlama Güz  200 9 ( 7 . Hafta)

2006 Pearson Education, Inc. All rights reserved.

23

Class View ve Object Browser

• Two features of Visual Studio to facilitate object-oriented applications

– Class View Window (Fig. 9.21)• Display the fields and methods for all classes in project

• When a class is selected, the class’s members are shown on the lower half of the window

– Object Browser (Fig. 9.22)• Lists all classes in the C# library (left frame)

- Learn the functionality provided by specific classes

• Methods provided on the upper-right frame

• Description of members appears in the lower-right frame

Page 24: Görsel C #  ile Windows Programlama Güz  200 9 ( 7 . Hafta)

2006 Pearson Education, Inc. All rights reserved.

24

Fig. 9.21 | Class View of class Time1 (Fig. 9.1) and class TimeTest (Fig. 9.2).

Page 25: Görsel C #  ile Windows Programlama Güz  200 9 ( 7 . Hafta)

2006 Pearson Education, Inc. All rights reserved.

25

Fig. 9.22 | Object Browser for class Math.

Page 26: Görsel C #  ile Windows Programlama Güz  200 9 ( 7 . Hafta)

2006 Pearson Education, Inc. All rights reserved.

26

• Kalıtım (inheritance) bir yazılımın tekrar tekrar kullanılabilmesine ve mevcut sınıflardan (base class) yeni sınıflar (derived class) oluşturulabilmesine imkan verir. Bu sayede yeni oluşan sınıf eski sınıfın üye değişkenleri ve metodlarını kullanabilmenin yanında kendisinin belirleyeceği yeni veya ek özellikleri de programına eklemiş olur.

Kalıtım (Inheritance)

Page 27: Görsel C #  ile Windows Programlama Güz  200 9 ( 7 . Hafta)

2006 Pearson Education, Inc. All rights reserved.

27

Kalıtım Örnekleri

Base class Derived classes

Student GraduateStudent, UndergraduateStudent

Shape Circle, Triangle, Rectangle

Loan CarLoan, HomeImprovementLoan, MortgageLoan

Employee Faculty, Staff, HourlyWorker, CommissionWorker

BankAccount CheckingAccount, SavingsAccount

Page 28: Görsel C #  ile Windows Programlama Güz  200 9 ( 7 . Hafta)

2006 Pearson Education, Inc. All rights reserved.

28

Kalıtım Hiyerarşisi

Page 29: Görsel C #  ile Windows Programlama Güz  200 9 ( 7 . Hafta)

2006 Pearson Education, Inc. All rights reserved.

29

• protected erişim public ile private arasında bir yerde bulunur. protected üye değişkenleri hem base class ve hem de derived class tarafından erişilebilir.

• derived class ın nesneleri base class ın private olarak tanımlanmış üye değişkenlerine erişemezler. Derived class ın nesneleri bu tür üye değişkenlere sadece public tanımlanmış base class metodları ile ulaşabilirler.

protected Erişim

Page 30: Görsel C #  ile Windows Programlama Güz  200 9 ( 7 . Hafta)

2006 Pearson Education, Inc. All rights reserved.

30

CommissionEmployeeFirst name, last name, SSN, commission rate, gross sale amount

BasePlusCommissionEmployeeFirst name, last name, SSN, commission rate, gross sale amount

Base salary

base Class-derived Class İlişkisi

Page 31: Görsel C #  ile Windows Programlama Güz  200 9 ( 7 . Hafta)

2006 Pearson Education, Inc. All rights reserved.

31

• C#’ta bütün sınıflar System.Object sınıfından türetilmiştir. Dolayısıyla bütün sınıflar System.Object sınıfının tüm metodlarını kullanabilirler. Bir sınıfın dolaylı olarak belirtilmese bile ima yoluyla System.Object sınıfından türetildiği bilinmelidir.

• Bir base class ın bir metodunun işlevi aynı metod adıyla derived class içerisinde değiştirilmek isteniyorsa metod override anahtar kelimesiyle tanımlanmalıdır. Derived class içerisinde override edilmesi muhtemel metodlar base class içerisinde virtual anahtar kelimesiyle tanımlanmalıdırlar.

• Yapıcılar kalıtım kapsamına girmezler. Derived class ların yapıcıları ilk iş olarak base class ın yapıcısını çağırırlar.

class CommissionEmployee

Page 32: Görsel C #  ile Windows Programlama Güz  200 9 ( 7 . Hafta)

2006 Pearson Education, Inc. All rights reserved.

32 1 // CommissionEmployee.cs

2 // CommissionEmployee class represents a commission employee.

3 public class CommissionEmployee : object

4 {

5 private string firstName;

6 private string lastName;

7 private string socialSecurityNumber;

8 private decimal grossSales; // gross weekly sales

9 private decimal commissionRate; // commission percentage

10

11 // five-parameter constructor

12 public CommissionEmployee( string first, string last, string ssn,

13 decimal sales, decimal rate )

14 {

15 // implicit call to object constructor occurs here

16 firstName = first;

17 lastName = last;

18 socialSecurityNumber = ssn;

19 GrossSales = sales; // validate gross sales via property

20 CommissionRate = rate; // validate commission rate via property

21 } // end five-parameter CommissionEmployee constructor

22

23 // read-only property that gets commission employee's first name

24 public string FirstName

25 {

26 get

27 {

28 return firstName;

29 } // end get

30 } // end property FirstName

CommissionEmployee.cs

(1 of 4)

Class CommissionEmployee extends class object

Implicit call to object constructor

Initialize instance variables

Declare private instance variables

Invoke properties GrossSales and CommissionRate to validate data

Page 33: Görsel C #  ile Windows Programlama Güz  200 9 ( 7 . Hafta)

2006 Pearson Education, Inc. All rights reserved.

3331

32 // read-only property that gets commission employee's last name

33 public string LastName

34 {

35 get

36 {

37 return lastName;

38 } // end get

39 } // end property LastName

40

41 // read-only property that gets

42 // commission employee's social security number

43 public string SocialSecurityNumber

44 {

45 get

46 {

47 return socialSecurityNumber;

48 } // end get

49 } // end property SocialSecurityNumber

CommissionEmployee.cs

(2 of 4)

Page 34: Görsel C #  ile Windows Programlama Güz  200 9 ( 7 . Hafta)

2006 Pearson Education, Inc. All rights reserved.

3450

51 // property that gets and sets commission employee's gross sales

52 public decimal GrossSales

53 {

54 get

55 {

56 return grossSales;

57 } // end get

58 set

59 {

60 grossSales = ( value < 0 ) ? 0 : value;

61 } // end set

62 } // end property GrossSales

63

64 // property that gets and sets commission employee's commission rate

65 public decimal CommissionRate

66 {

67 get

68 {

69 return commissionRate;

70 } // end get

71 set

72 {

73 commissionRate = ( value > 0 && value < 1 ) ? value : 0;

74 } // end set

75 } // end property CommissionRate

CommissionEmployee.cs

(3 of 4)

Page 35: Görsel C #  ile Windows Programlama Güz  200 9 ( 7 . Hafta)

2006 Pearson Education, Inc. All rights reserved.

3576

77 // calculate commission employee's pay

78 public decimal Earnings()

79 {

80 return commissionRate * grossSales;

81 } // end method Earnings

82

83 // return string representation of CommissionEmployee object

84 public override string ToString()

85 {

86 return string.Format(

87 "{0}: {1} {2}\n{3}: {4}\n{5}: {6:C}\n{7}: {8:F2}",

88 "commission employee", FirstName, LastName,

89 "social security number", SocialSecurityNumber,

90 "gross sales", GrossSales, "commission rate", CommissionRate );

91 } // end method ToString

92 } // end class CommissionEmployee

CommissionEmployee.cs

(4 of 4)

Calculate earnings

Override method ToString of class object

Page 36: Görsel C #  ile Windows Programlama Güz  200 9 ( 7 . Hafta)

2006 Pearson Education, Inc. All rights reserved.

36 1 // CommissionEmployeeTest.cs

2 // Testing class CommissionEmployee.

3 using System;

4

5 public class CommissionEmployeeTest

6 {

7 public static void Main( string[] args )

8 {

9 // instantiate CommissionEmployee object

10 CommissionEmployee employee = new CommissionEmployee( "Sue",

11 "Jones", "222-22-2222", 10000.00M, .06M );

12

13 // display commission employee data

14 Console.WriteLine(

15 "Employee information obtained by properties and methods: \n" );

16 Console.WriteLine( "{0} {1}", "First name is",

17 employee.FirstName );

18 Console.WriteLine( "{0} {1}", "Last name is",

19 employee.LastName );

20 Console.WriteLine( "{0} {1}", "Social security number is",

21 employee.SocialSecurityNumber );

22 Console.WriteLine( "{0} {1:C}", "Gross sales are",

23 employee.GrossSales );

24 Console.WriteLine( "{0} {1:F2}", "Commission rate is",

25 employee.CommissionRate );

26 Console.WriteLine( "{0} {1:C}", "Earnings are",

27 employee.Earnings() );

CommissionEmployeeTest.cs

(1 of 2)

Instantiate CommissionEmployee object

Use CommissionEmployee’s properties to retrieve and change the object’s instance variable values

Page 37: Görsel C #  ile Windows Programlama Güz  200 9 ( 7 . Hafta)

2006 Pearson Education, Inc. All rights reserved.

3728

29 employee.GrossSales = 5000.00M; // set gross sales

30 employee.CommissionRate = .1M; // set commission rate

31

32 Console.WriteLine( "\n{0}:\n\n{1}",

33 "Updated employee information obtained by ToString", employee );

34 Console.WriteLine( "earnings: {0:C}", employee.Earnings() );

35 } // end Main

36 } // end class CommissionEmployeeTest Employee information obtained by properties and methods: First name is Sue Last name is Jones Social security number is 222-22-2222 Gross sales are $10,000.00 Commission rate is 0.06 Earnings are $600.00 Updated employee information obtained by ToString: commission employee: Sue Jones social security number: 222-22-2222 gross sales: $5,000.00 commission rate: 0.10 earnings: $500.00

CommissionEmployeeTest.cs

(2 of 2)

Implicitly call the object’s ToString method

Page 38: Görsel C #  ile Windows Programlama Güz  200 9 ( 7 . Hafta)

2006 Pearson Education, Inc. All rights reserved.

38

• CommissionEmployee sınıfını tanımlarken kullanılan programa çok benzer. Farklı olarak sadece baseSalary adında private bir üye değişkeni ve BaseSalary adında bir üye metodu eklenmiştir.

class BasePlusCommissionEmployee

Page 39: Görsel C #  ile Windows Programlama Güz  200 9 ( 7 . Hafta)

2006 Pearson Education, Inc. All rights reserved.

39 1 // BasePlusCommissionEmployee.cs

2 // BasePlusCommissionEmployee class represents an employee that receives

3 // a base salary in addition to a commission.

4 public class BasePlusCommissionEmployee

5 {

6 private string firstName;

7 private string lastName;

8 private string socialSecurityNumber;

9 private decimal grossSales; // gross weekly sales

10 private decimal commissionRate; // commission percentage

11 private decimal baseSalary; // base salary per week

12

13 // six-parameter constructor

14 public BasePlusCommissionEmployee( string first, string last,

15 string ssn, decimal sales, decimal rate, decimal salary )

16 {

17 // implicit call to object constructor occurs here

18 firstName = first;

19 lastName = last;

20 socialSecurityNumber = ssn;

21 GrossSales = sales; // validate gross sales via property

22 CommissionRate = rate; // validate commission rate via property

23 BaseSalary = salary; // validate base salary via property

24 } // end six-parameter BasePlusCommissionEmployee constructor

BasePlusCommissionEmployee.cs

(1 of 5)

Add instance variable baseSalary

Use property BaseSalary to validate data

Page 40: Görsel C #  ile Windows Programlama Güz  200 9 ( 7 . Hafta)

2006 Pearson Education, Inc. All rights reserved.

4025

26 // read-only property that gets

27 // base-salaried commission employee's first name

28 public string FirstName

29 {

30 get

31 {

32 return firstName;

33 } // end get

34 } // end property FirstName

35

36 // read-only property that gets

37 // base-salaried commission employee's last name

38 public string LastName

39 {

40 get

41 {

42 return lastName;

43 } // end get

44 } // end property LastName

45

46 // read-only property that gets

47 // base-salaried commission employee's social security number

48 public string SocialSecurityNumber

49 {

50 get

51 {

52 return socialSecurityNumber;

53 } // end get

54 } // end property SocialSecurityNumber

BasePlusCommissionEmployee.cs

(2 of 5)

Page 41: Görsel C #  ile Windows Programlama Güz  200 9 ( 7 . Hafta)

2006 Pearson Education, Inc. All rights reserved.

4155

56 // property that gets and sets

57 // base-salaried commission employee's gross sales

58 public decimal GrossSales

59 {

60 get

61 {

62 return grossSales;

63 } // end get

64 set

65 {

66 grossSales = ( value < 0 ) ? 0 : value;

67 } // end set

68 } // end property GrossSales

69

70 // property that gets and sets

71 // base-salaried commission employee's commission rate

72 public decimal CommissionRate

73 {

74 get

75 {

76 return commissionRate;

77 } // end get

78 set

79 {

80 commissionRate = ( value > 0 && value < 1 ) ? value : 0;

81 } // end set

82 } // end property CommissionRate

BasePlusCommissionEmployee.cs

(3 of 5)

Page 42: Görsel C #  ile Windows Programlama Güz  200 9 ( 7 . Hafta)

2006 Pearson Education, Inc. All rights reserved.

4283

84 // property that gets and sets

85 // base-salaried commission employee's base salary

86 public decimal BaseSalary

87 {

88 get

89 {

90 return baseSalary;

91 } // end get

92 set

93 {

94 baseSalary = ( value < 0 ) ? 0 : value;

95 } // end set

96 } // end property BaseSalary

97

98 // calculate earnings

99 public decimal Earnings()

100 {

101 return BaseSalary + ( CommissionRate * GrossSales );

102 } // end method earnings

BasePlusCommissionEmployee.cs

(4 of 5)

Validates data and sets instance variable baseSalary

Update method Earnings to calculate the earnings of a base-salaried commission employee

Page 43: Görsel C #  ile Windows Programlama Güz  200 9 ( 7 . Hafta)

2006 Pearson Education, Inc. All rights reserved.

43103

104 // return string representation of BasePlusCommissionEmployee

105 public override string ToString()

106 {

107 return string.Format(

108 "{0}: {1} {2}\n{3}: {4}\n{5}: {6:C}\n{7}: {8:F2}\n{9}: {10:C}",

109 "base-salaried commission employee", FirstName, LastName,

110 "social security number", SocialSecurityNumber,

111 "gross sales", GrossSales, "commission rate", CommissionRate,

112 "base salary", BaseSalary );

113 } // end method ToString

114 } // end class BasePlusCommissionEmployee

BasePlusCommissionEmployee.cs

(5 of 5)

Update method ToString to display base salary

Page 44: Görsel C #  ile Windows Programlama Güz  200 9 ( 7 . Hafta)

2006 Pearson Education, Inc. All rights reserved.

44 1 // BasePlusCommissionEmployeeTest.cs

2 // Testing class BasePlusCommissionEmployee.

3 using System;

4

5 public class BasePlusCommissionEmployeeTest

6 {

7 public static void Main( string[] args )

8 {

9 // instantiate BasePlusCommissionEmployee object

10 BasePlusCommissionEmployee employee =

11 new BasePlusCommissionEmployee( "Bob", "Lewis",

12 "333-33-3333", 5000.00M, .04M, 300.00M );

13

14 // display base-salaried commission employee data

15 Console.WriteLine(

16 "Employee information obtained by properties and methods: \n" );

17 Console.WriteLine( "{0} {1}", "First name is",

18 employee.FirstName );

19 Console.WriteLine( "{0} {1}", "Last name is",

20 employee.LastName );

21 Console.WriteLine( "{0} {1}", "Social security number is",

22 employee.SocialSecurityNumber );

23 Console.WriteLine( "{0} {1:C}", "Gross sales are",

24 employee.GrossSales );

25 Console.WriteLine( "{0} {1:F2}", "Commission rate is",

26 employee.CommissionRate );

27 Console.WriteLine( "{0} {1:C}", "Earnings are",

28 employee.Earnings() );

29 Console.WriteLine( "{0} {1:C}", "Base salary is",

30 employee.BaseSalary );

BasePlusCommissionEmployeeTest.cs

(1 of 2)

Instantiate BasePlusCommissionEmployee object

Use BasePluCommissionEmployee’s properties to retrieve and change the object’s instance variable values

Page 45: Görsel C #  ile Windows Programlama Güz  200 9 ( 7 . Hafta)

2006 Pearson Education, Inc. All rights reserved.

4531

32 employee.BaseSalary = 1000.00M; // set base salary

33

34 Console.WriteLine( "\n{0}:\n\n{1}",

35 "Updated employee information obtained by ToString", employee );

36 Console.WriteLine( "earnings: {0:C}", employee.Earnings() );

37 } // end Main

38 } // end class BasePlusCommissionEmployeeTest Employee information obtained by properties and methods: First name is Bob Last name is Lewis Social security number is 333-33-3333 Gross sales are $5,000.00 Commission rate is 0.04 Earnings are $500.00 Base salary is $300.00 Updated employee information obtained by ToString: base-salaried commission employee: Bob Lewis social security number: 333-33-3333 gross sales: $5,000.00 commission rate: 0.04 base salary: $1,000.00 earnings: $1,200.00

BasePlusCommissionEmployeeTest.cs

(2 of 2)

Implicitly call the object’s ToString method

Page 46: Görsel C #  ile Windows Programlama Güz  200 9 ( 7 . Hafta)

2006 Pearson Education, Inc. All rights reserved.

46

Hatırlatma.......

Bir sınıftan kod parçası kopyalayıp başka bir sınıfı oluşturmak muhtemel hataları da beraberinde kopyalamak demektir. Böyle bir yaklaşım yerine (kopyala ve yapıştır) kalıtım kullanmak daha doğrudur.

Page 47: Görsel C #  ile Windows Programlama Güz  200 9 ( 7 . Hafta)

2006 Pearson Education, Inc. All rights reserved.

47 1 // BasePlusCommissionEmployee2.cs

2 // BasePlusCommissionEmployee2 inherits from class CommissionEmployee.

3 public class BasePlusCommissionEmployee2 : CommissionEmployee

4 {

5 private decimal baseSalary; // base salary per week

6

7 // six-parameter derived class constructor

8 // with call to base class CommissionEmployee constructor

9 public BasePlusCommissionEmployee2( string first, string last,

10 string ssn, decimal sales, decimal rate, decimal salary )

11 : base( first, last, ssn, sales, rate )

12 {

13 BaseSalary = salary; // validate base salary via property

14 } // end six-parameter BasePlusCommissionEmployee2 constructor

15

16 // property that gets and sets

17 // base-salaried commission employee's base salary

18 public decimal BaseSalary

19 {

20 get

21 {

22 return baseSalary;

23 } // end get

24 set

25 {

26 baseSalary = ( value < 0 ) ? 0 : value;

27 } // end set

28 } // end property BaseSalary

BasePlusCommissionEmployee2.cs

(1 of 2)

Class BasePluCommissionEmployee2 is a derived class of CommissionEmployee

Invoke the base class constructor using the base class constructor call syntax

Page 48: Görsel C #  ile Windows Programlama Güz  200 9 ( 7 . Hafta)

2006 Pearson Education, Inc. All rights reserved.

4829

30 // calculate earnings

31 public override decimal Earnings()

32 {

33 // not allowed: commissionRate and grossSales private in base class

34 return baseSalary + ( commissionRate * grossSales );

35 } // end method Earnings

36

37 // return string representation of BasePlusCommissionEmployee2

38 public override string ToString()

39 {

40 // not allowed: attempts to access private base class members

41 return string.Format(

42 "{0}: {1} {2}\n{3}: {4}\n{5}: {6:C}\n{7}: {8:F2}\n{9}: {10:C}",

43 "base-salaried commission employee", firstName, lastName,

44 "social security number", socialSecurityNumber,

45 "gross sales", grossSales, "commission rate", commissionRate,

46 "base salary", baseSalary );

47 } // end method ToString

48 } // end class BasePlusCommissionEmployee2

BasePlusCommissionEmployee2.cs

(2 of 2)Compiler generates errors because base class’s instance variable are private

Page 49: Görsel C #  ile Windows Programlama Güz  200 9 ( 7 . Hafta)

2006 Pearson Education, Inc. All rights reserved.

49 1 // CommissionEmployee2.cs

2 // CommissionEmployee2 with protected instance variables.

3 public class CommissionEmployee2

4 {

5 protected string firstName;

6 protected string lastName;

7 protected string socialSecurityNumber;

8 protected decimal grossSales; // gross weekly sales

9 protected decimal commissionRate; // commission percentage

10

11 // five-parameter constructor

12 public CommissionEmployee2( string first, string last, string ssn,

13 decimal sales, decimal rate )

14 {

15 // implicit call to object constructor occurs here

16 firstName = first;

17 lastName = last;

18 socialSecurityNumber = ssn;

19 GrossSales = sales; // validate gross sales via property

20 CommissionRate = rate; // validate commission rate via property

21 } // end five-parameter CommissionEmployee2 constructor

22

23 // read-only property that gets commission employee's first name

24 public string FirstName

25 {

26 get

27 {

28 return firstName;

29 } // end get

30 } // end property FirstName

CommissionEmployee2.cs

(1 of 4)

Declare protected instance variables

Page 50: Görsel C #  ile Windows Programlama Güz  200 9 ( 7 . Hafta)

2006 Pearson Education, Inc. All rights reserved.

5031

32 // read-only property that gets commission employee's last name

33 public string LastName

34 {

35 get

36 {

37 return lastName;

38 } // end get

39 } // end property LastName

40

41 // read-only property that gets

42 // commission employee's social security number

43 public string SocialSecurityNumber

44 {

45 get

46 {

47 return socialSecurityNumber;

48 } // end get

49 } // end property SocialSecurityNumber

CommissionEmployee2.cs

(2 of 4)

Page 51: Görsel C #  ile Windows Programlama Güz  200 9 ( 7 . Hafta)

2006 Pearson Education, Inc. All rights reserved.

5150

51 // property that gets and sets commission employee's gross sales

52 public decimal GrossSales

53 {

54 get

55 {

56 return grossSales;

57 } // end get

58 set

59 {

60 grossSales = ( value < 0 ) ? 0 : value;

61 } // end set

62 } // end property GrossSales

63

64 // property that gets and sets commission employee's commission rate

65 public decimal CommissionRate

66 {

67 get

68 {

69 return commissionRate;

70 } // end get

71 set

72 {

73 commissionRate = ( value > 0 && value < 1 ) ? value : 0;

74 } // end set

75 } // end property CommissionRate

CommissionEmployee2.cs

(3 of 4)

Page 52: Görsel C #  ile Windows Programlama Güz  200 9 ( 7 . Hafta)

2006 Pearson Education, Inc. All rights reserved.

5276

77 // calculate commission employee's pay

78 public virtual decimal Earnings()

79 {

80 return commissionRate * grossSales;

81 } // end method Earnings

82

83 // return string representation of CommissionEmployee object

84 public override string ToString()

85 {

86 return string.Format(

87 "{0}: {1} {2}\n{3}: {4}\n{5}: {6:C}\n{7}: {8:F2}",

88 "commission employee", firstName, lastName,

89 "social security number", socialSecurityNumber,

90 "gross sales", grossSales, "commission rate", commissionRate );

91 } // end method ToString

92 } // end class CommissionEmployee2

CommissionEmployee2.cs

(4 of 4)

Mark Earnings as virtual so the derived class can override the method

Page 53: Görsel C #  ile Windows Programlama Güz  200 9 ( 7 . Hafta)

2006 Pearson Education, Inc. All rights reserved.

53 1 // BasePlusCommissionEmployee3.cs

2 // BasePlusCommissionEmployee3 inherits from CommissionEmployee2 and has

3 // access to CommissionEmployee2's protected members.

4 public class BasePlusCommissionEmployee3 : CommissionEmployee2

5 {

6 private decimal baseSalary; // base salary per week

7

8 // six-parameter derived class constructor

9 // with call to base class CommissionEmployee constructor

10 public BasePlusCommissionEmployee3( string first, string last,

11 string ssn, decimal sales, decimal rate, decimal salary )

12 : base( first, last, ssn, sales, rate )

13 {

14 BaseSalary = salary; // validate base salary via property

15 } // end six-parameter BasePlusCommissionEmployee3 constructor

16

17 // property that gets and sets

18 // base-salaried commission employee's base salary

19 public decimal BaseSalary

20 {

21 get

22 {

23 return baseSalary;

24 } // end get

25 set

26 {

27 baseSalary = ( value < 0 ) ? 0 : value;

28 } // end set

29 } // end property BaseSalary

BasePlusCommissionEmployee3.cs

(1 of 2)

Must call base class’s constructor

Page 54: Görsel C #  ile Windows Programlama Güz  200 9 ( 7 . Hafta)

2006 Pearson Education, Inc. All rights reserved.

5430

31 // calculate earnings

32 public override decimal Earnings()

33 {

34 return baseSalary + ( commissionRate * grossSales );

35 } // end method Earnings

36

37 // return string representation of BasePlusCommissionEmployee3

38 public override string ToString()

39 {

40 return string.Format(

41 "{0}: {1} {2}\n{3}: {4}\n{5}: {6:C}\n{7}: {8:F2}\n{9}: {10:C}",

42 "base-salaried commission employee", firstName, lastName,

43 "social security number", socialSecurityNumber,

44 "gross sales", grossSales, "commission rate", commissionRate,

45 "base salary", baseSalary );

46 } // end method ToString

47 } // end class BasePlusCommissionEmployee3

BasePlusCommissionEmployee3.cs

(2 of 2)

Overrides base class’s Earnings method

Directly access base class’s protected instance variables

Page 55: Görsel C #  ile Windows Programlama Güz  200 9 ( 7 . Hafta)

2006 Pearson Education, Inc. All rights reserved.

55 1 // BasePlusCommissionEmployeeTest3.cs

2 // Testing class BasePlusCommissionEmployee3.

3 using System;

4

5 public class BasePlusCommissionEmployeeTest3

6 {

7 public static void Main( string[] args )

8 {

9 // instantiate BasePlusCommissionEmployee3 object

10 BasePlusCommissionEmployee3 basePlusCommissionEmployee =

11 new BasePlusCommissionEmployee3( "Bob", "Lewis",

12 "333-33-3333", 5000.00M, .04M, 300.00M );

13

14 // display base-salaried commission employee data

15 Console.WriteLine(

16 "Employee information obtained by properties and methods: \n" );

17 Console.WriteLine( "{0} {1}", "First name is",

18 basePlusCommissionEmployee.FirstName );

19 Console.WriteLine( "{0} {1}", "Last name is",

20 basePlusCommissionEmployee.LastName );

21 Console.WriteLine( "{0} {1}", "Social security number is",

22 basePlusCommissionEmployee.SocialSecurityNumber );

23 Console.WriteLine( "{0} {1:C}", "Gross sales are",

24 basePlusCommissionEmployee.GrossSales );

25 Console.WriteLine( "{0} {1:F2}", "Commission rate is",

26 basePlusCommissionEmployee.CommissionRate );

27 Console.WriteLine( "{0} {1:C}", "Earnings are",

28 basePlusCommissionEmployee.Earnings() );

29 Console.WriteLine( "{0} {1:C}", "Base salary is",

30 basePlusCommissionEmployee.BaseSalary );

BasePlusCommissionEmployeeTest3.cs

(1 of 2)

Instantiate BasePlusCommissionEmployee3 object

Use BasePluCommissionEmployee3’s properties to retrieve and change the object’s instance variable values

Page 56: Görsel C #  ile Windows Programlama Güz  200 9 ( 7 . Hafta)

2006 Pearson Education, Inc. All rights reserved.

5631

32 basePlusCommissionEmployee.BaseSalary = 1000.00M; // set base salary

33

34 Console.WriteLine( "\n{0}:\n\n{1}",

35 "Updated employee information obtained by ToString",

36 basePlusCommissionEmployee );

37 Console.WriteLine( "earnings: {0:C}",

38 basePlusCommissionEmployee.Earnings() );

39 } // end Main

40 } // end class BasePlusCommissionEmployeeTest3

Employee information obtained by properties and methods: First name is Bob Last name is Lewis Social security number is 333-33-3333 Gross sales are $5,000.00 Commission rate is 0.04 Earnings are $500.00 Base salary is $300.00 Updated employee information obtained by ToString: base-salaried commission employee: Bob Lewis social security number: 333-33-3333 gross sales: $5,000.00 commission rate: 0.04 base salary: $1,000.00 earnings: $1,200.00

BasePlusCommissionEmployeeTest3.cs

(2 of 2)

Implicitly call the object’s ToString method

Page 57: Görsel C #  ile Windows Programlama Güz  200 9 ( 7 . Hafta)

2006 Pearson Education, Inc. All rights reserved.

57

Equals

Finalize

GetHashCode

GetType

MemberwiseClone

ReferenceEquals

ToString

System.Object Sınıfının Metodları

Page 58: Görsel C #  ile Windows Programlama Güz  200 9 ( 7 . Hafta)

2006 Pearson Education, Inc. All rights reserved.

58

Method Description

Equals

This method compares two objects for equality and returns true if they are equal and false otherwise. The method takes any object as an argument. When objects of a particular class must be compared for equality, the class should override method Equals to compare the contents of the two objects. The method’s implementation should meet the following requirements:

• It should return false if the argument is null.

• It should return true if an object is compared to itself, as in object1.Equals( object1 ).

• It should return true only if both object1.Equals( object2 ) and object2.Equals( object1 ) would return true.

• For three objects, if object1.Equals( object2 ) returns true and object2.Equals( object3 ) returns true, then object1.Equals( object3 ) should also return true.

• A class that overrides the method Equals should also override the method GetHashCode to ensure that equal objects have identical hashcodes. The default Equals implementation determines only whether two references refer to the same object in memory.

Finalize This method cannot be explicitly declared or called. When a class contains a destructor, the compiler implicitly renames it to override the protected method Finalize, which is called only by the garbage collector before it reclaims an object’s memory. The garbage collector is not guaranteed to reclaim an object, thus it is not guaranteed that an object’s Finalize method will execute. When a derived class’s Finalize method executes, it performs its task, then invokes the base class’s Finalize method. Finalize’s default implementation is a placeholder that simply invokes the base class’s Finalize method.

Page 59: Görsel C #  ile Windows Programlama Güz  200 9 ( 7 . Hafta)

2006 Pearson Education, Inc. All rights reserved.

59

Method Description

GetHashCode A hashtable is a data structure that relates one object, called the key, to another object, called the value. We discuss Hashtable in Chapter 27, Collections. When initially inserting a value into a hashtable, the key’s GetHashCode method is called. The hashcode value returned is used by the hashtable to determine the location at which to insert the corresponding value. The key’s hashcode is also used by the hashtable to locate the key’s corresponding value.

GetType Every object knows its own type at execution time. Method GetType (used in Section 11.5) returns an object of class Type (namespace System) that contains information about the object’s type, such as its class name (obtained from Type property FullName).

MemberwiseClone This protected method, which takes no arguments and returns an object reference, makes a copy of the object on which it is called. The implementation of this method performs a shallow copy—instance variable values in one object are copied into another object of the same type. For reference types, only the references are copied.

Reference-Equals This static method takes two object arguments and returns true if two objects are the same instance or if they are null references. Otherwise, it returns false.

ToString This method (introduced in Section 7.4) returns a string representation of an object. The default implementation of this method returns the namespace followed by a dot and the class name of the object’s class.