본문 바로가기
Visual Basic .NET/Class

How to Restrict Access to Class Members?

by edupicker(체르니) 2008. 6. 23.

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 her
code 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.

The following program, restrictaccesstoclass.vb, creates an Person class that uses both Public and Private members.
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:
사용자 삽입 이미지