News:

Choose a design and let our professionals help you build a successful website   - ITAcumens

Main Menu

Code implementation in Encapsualtion - C#.net

Started by arun, Jan 11, 2008, 02:25 PM

Previous topic - Next topic

arun

BankAccountProtected's protected method because it is a derived class. This is a common pattern in polymorphism because derived classes often have a responsibility to call virtual base class methods to ensure critical functionality has the opportunity to execute. You would consult the method documentation to see if this was necessary. Without a protected access modifier, your only option would have been to make the base class method public; which, as explained earlier, is dangerous.

you can implement the following code:

BankAccountProtected[] bankAccts = new BankAccountProtected[2];
bankAccts[0] = new SavingsAccount();
bankAccts[1] = new CheckingAccount();

foreach (BankAccountProtected acct in bankAccts)
{
    // call public method, which invokes protected virtual methods
    acct.CloseAccount();
}

Since both SavingsAccount and CheckingAccount derive from BankAccountProtected, you can assign them to the bankAccts array.  They both override the protected virtual methods of BankAccountProtected, so it is the SavingsAccount and CheckingAccount methods that are called when CloseAccount in BankAccountProtected executes. Remember that the only reason the methods of SavingsAccount and CheckingAccount can call their virtual base class methods, as in the case of DeleteAccountFromDB, is because the virtual base class methods are marked with the protected access modifier.
A Quick Word on internal and protected internal Access Modifiers

In practice, most of the code you write will involve the public, private, and protected access modifiers.  However, there are two more access modifiers that you can use in more sophisticated scenarios:  internal and protected internal.

You would use internal whenever you created a separate class library and you don't want any code outside of the library to access the code with internal access.  The protected internal is a combination of the two access modifiers it is named after, which means either protected or internal.
Access Modifiers for Types

So far, the discussion of access modifiers has only applied to the members of types.  However, the rules are different for the types themselves.  When talking about types, I'm referring to all of the C# types, including classes, structs, interfaces, delegates, and enums. Nested types, such as a class defined within the scope of a class, are considered type members and fall under the same access rules as other type members.
- Arun Kumar