Encapsulation by using Public Access Specifier in VB.NET

This article is about how to implement Encapsulation by using Public access specifier.
  • 2179

An access specifier defines the scope of a class member. A class member refers to the variables and functions in a class. A program can have one or more classes. You may want some member of a class to be accessible to other classes. But, you may not want some other member of the class to be accessible outside the class.

You can use various types of access specifier to specify the extent of the visibility of a class member such as public, private, protected, internal, protected internal.

The public access specifier

The public access specifier allows a class to expose its member variables and member functions to other functions and objects. Any member that is declared public can be accessed from outside the class. The following is an example of the use of the public access specifier:

using System;
class car
{
    private string CarColor; //Since the variable is private, it cannot be accessed outside the class definition.
}
class Bike
{
    public string BikeColor; //Since the variable is public, it can be accessed outside the class definition.
}
class Result
{
    static void Main(string[] args)
    {
        car Ford = new car();
        Bike Honda = new Bike();
        /*The . operator is used to access member data and functions */
        Ford.CarColor = "red"; /* Error! Cannot access private member */
        Honda.BikeColor = "blue";
        Console.ReadLine();
    }
}

In the preceding example, the CarColor variable cannot be accessed from any function outside the Car class. On the other hand, the BikeColor variable is a public member. Therefore, it can be accessed from outside the class and if you debug the program a dialog box appears and shows build errors:

asa.gif

Categories

More Articles

© 2019 DotNetHeaven. All rights reserved.