11.07.2015 Views

Beginning C# 2008-from Novice-to-professional - A2Z Dotnet

Beginning C# 2008-from Novice-to-professional - A2Z Dotnet

Beginning C# 2008-from Novice-to-professional - A2Z Dotnet

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

CHAPTER 7 ■ LEARNING ABOUT COMPONENTS AND OBJECT HIERARCHIES 179namespace LibTax.Surtax{internal class TaxEngine : BaseTaxEngine {public override double CalculateTaxToPay(ITaxAccount account) {double taxToPay = base.CalculateTaxToPay(account);if (_calculatedTaxable > 400) {taxToPay += 10;}return taxToPay;}public override ITaxAccount CreateTaxAccount() {throw new Exception("The method or operation is not implemented.");}}}In the implementation of CalculateTaxToPay(), we replace the virtual keyword with override,implying that the functionality of TaxEngine replaces the functionality of BaseTaxEngine.However, if TaxEngine is called, and the TaxEngine.CalculateTaxToPay() implementation isempty, then tax is not calculated. Since our fictional country calculates the basic tax similarly<strong>to</strong> most countries, the functionality of BaseTaxEngine.CalculateTaxToPay() can be used. Thus,the first line of TaxEngine.CalculateTaxToPay() is base.CalculateTaxToPay(), meaning thebase class (BaseTaxEngine) method CalculateTaxToPay() is called.Calling the base class results in calculating a basic tax <strong>to</strong> pay amount. We need <strong>to</strong> figureout if a surtax applies, and that is where the protected data member _calculatedTaxablecomes in<strong>to</strong> play. Having called BaseTaxEngine.CalculateTaxToPay(), the data member_calculatedTaxable is assigned and contains the amount that is being taxed. Thus, TaxEngine.CalculateTaxToPay() can make a decision if more than 400 currency units have been earned.And if so, then the variable taxToPay is incremented with another 10 currency units. Had_calculatedTaxable not existed, TaxEngine.CalculateTaxToPay() would have needed <strong>to</strong> callthe base class functionality <strong>to</strong> get the basic tax rate, and then recalculate the taxable monies <strong>to</strong>figure out if the surtax applied.■Note When you override methods, you are saying that you need something special. This does not implythat the base class functionality will be called. It implies that you might call the base class functionality andperform some additional operations. Thus, when designing base class functionality, it is important <strong>to</strong> trackcalculations or operations using protected data members. The data members avoid having derived classesperform the same operations multiple times, slowing down the application and avoiding potential errors.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!