This is an example for Inheritance and it is using the get() and set() method. Employee class has two data field empNum & empSal. I wish to convert this program to automatic property. During the conversation empNum's access modifier private will become public. But empSal is access modifier is protected. I wish to know its change during conversation.
//p243
//Declaring empSal as protected and accessing it with CommissionEmployee
using System;
public class DemoEmployees
{
public static void Main()
{
Employee clerk = new Employee();
CommissionEmployee salesperson = new CommissionEmployee();
clerk.SetEmpNum(5612);
clerk.SetEmpSal(425.00);
salesperson.SetEmpNum(3198);
salesperson.SetRate(0.07);
Console.WriteLine("\nCleark #{0} makes {1} per week", clerk.GetEmpNum(), clerk.GetEmpSal().ToString("C2"));
Console.WriteLine("\nSalesperson #{0} makes {1} per week", salesperson.GetEmpNum(), salesperson.GetEmpSal().ToString("C2"));
Console.WriteLine("...plus {0} percent commission on all sales", salesperson.GetRate());
}
}
internal class Employee
{
private int empNum;
protected double empSal;//empSal is protected, not private
public int GetEmpNum()
{
return empNum;
}
public void SetEmpNum(int num)
{
empNum = num;
}
public double GetEmpSal()
{
return empSal;
}
public void SetEmpSal(double sal)
{
empSal = sal;
}
}
class CommissionEmployee : Employee
{
private double commissionRate;
public double GetRate()
{
return commissionRate;
}
public void SetRate(double rate)
{
commissionRate = rate;
empSal = 0;//If empSal was private, this would be illegal
}
}
/*
Cleark #5612 makes $425.00 per week
Salesperson #3198 makes $0.00 per week
...plus 0.07 percent commission on all sales
*/
Loading
Posted Dec 29, 2011, 11:50 AM
VulpesPosted Dec 29, 2011, 11:47 AM
The automatic property itself can have any modifier (and the modifiers for the 'get' and 'set' accessors don't have to be the same) but the backing field is always private.
In a sense this doesn't matter because the field is always accessed through the property in any case. So, as long as the property itself is non-private a derived class will still have access to the underlying field even though it is private.
Posted Dec 29, 2011, 11:32 AM
VulpesPosted Dec 29, 2011, 11:22 AM