As mentioned at the beginning of the chapter, encapsulation , the capability to hide data and methods to stop them from cluttering up the rest of your code, is one of the biggest advantages of OOP. Encapsulating data and methods not only ensures that they don't clutter up the rest of your code, it also ensures that the rest of your code doesn't interfere with them. You can use access modifiers to set the allowed access to not only classes, but also to all members of those classes. Here are the available access modifiers:
The following five accessibility levels can be specified using the access modifiers: public , protected , internal , internal protected , and private .
Note that if you don't specify an access modifier for a type or type member, the default access modifier is private . For example, you might have noticed that we explicitly declared the Addem method public in the Calculator class (see Listing 3.1). We did that so we could access Addem using an object of the Calculator class in the program's main class, ch03_01 . If we had another method, Subtractem , that we declared private in the Calculator class, Subtractem would be private to the Calculator class, which means that we can't access it using objects of that class. For example, this code won't compile: class ch03_01 { static void Main() { Calculator obj = new Calculator(); System.Console.WriteLine("2 + 3 = {0}", obj.Addem(2, 3)); //This won't work!! System.Console.WriteLine("3 - 2 = {0}", obj.Subtractem(3, 2)); } } class Calculator { public long Addem(int value1, int value2) { return value1 + value2; } private long Subtractem(int value1, int value2) { return value1 - value2; } } Here's the error you'd see if you tried to compile this code: ch03_01.cs(7,49): error CS0122: 'Calculator.Subtractem(int, int)' is inaccessible due to its protection level We'll see the protected keyword, which you use primarily with class inheritance, in the next chapter, and discuss the internal keyword in more depth in Chapter 13, "Understanding C# Assemblies and Security," when we discuss assemblies.
It's now time to get into some in-depth OOP as we create class members, including fields, methods, and properties. |