How to Restrict Access to Class Members?
When you create a class, you should think of the class as a “black box,” meaning, to use the class, you do not need to know how the class performs its processing, but rather, what processing the class performs.
Your cellular phone, for example, is a good example of a black box. To use the phone, you do not need to understand how the phone’s receiver converts the signals it receives into the images that appear on the LCD screen.
Instead, you simply must know how to turn the phone on, push buttons, and increase or decrease the volume when you listen to music.
Likewise, to use your class, another programmer should only need to know the class’s callable methods and usable member variables. The programmer does not need to understand how each of your class methods work,
but rather, the programmer must only know which parameters his or hercode must pass to the methods.
To help you better treat your classes as black boxes, Visual Basic .NET lets you hide class member variables and methods that are private to the class so that code outside of the class cannot access them.
Access Control Modifier |
Meaning |
Friend |
The member is only available within the current project. |
Private |
The member is only available within the class. |
Protected |
The member is available within the class and classes that inherit the class. |
Protected Friend |
The member is available within the current project and within classes that inherit the class. |
Public |
The member is available to code outside of the class. |
Table : Visual Basic .NET Access Modifiers that Programmers Can
Use to Control Access to Class Members
Now, let me show a sample.
Outside of the class, the code can access the Public members directly, using the dot operator.
If code outside of the class tries to access a Private member directly, the compiler will generate a syntax error. Within the class, however, the code can access Private members directly.
source code:
execution:
'Visual Basic .NET > Class' 카테고리의 다른 글
A destructor method in a class (0) | 2008.06.26 |
---|---|
using MyBase (0) | 2008.06.25 |
understand the inherited constructors of class (0) | 2008.06.25 |
how about using Multiple Constructors to Support Different Parameters (0) | 2008.06.24 |
how to Initialize Class Member Variables (0) | 2008.06.24 |