In Visual Basic, the access level "protected" (Protected) is intended for encapsulation — it allows class members to be accessible only within the class itself and its derived classes. This is important for organizing OOP architecture as well as for limiting direct access to the internal implementation of an object.
Historically, in classic VB6, such flexibility was almost nonexistent, but starting with VB.NET, full access modifiers that conform to modern OOP standards were introduced.
Errors in organizing access can lead to improper use of a class's properties or methods and, potentially, violations of encapsulation. For example, a public method will be available to everyone, including external components, while a protected method restricts access to derived classes.
In VB.NET, the modifiers Protected, Protected Friend, and Private are available. Protected is visible only within the class and its descendants, Protected Friend — within the assembly and its descendants, Private — only within the declaring class.
Example code:
Public Class Animal Protected Sub Eat() Console.WriteLine("Eating...") End Sub Private Sub Sleep() Console.WriteLine("Sleeping...") End Sub End Class Public Class Dog Inherits Animal Public Sub PerformEat() Eat() ' Accessible: Protected End Sub ' Sleep() not accessible: Private End Class
Key features:
Can the Protected modifier provide visibility of a class member to all classes in the assembly?
No, only to the class itself and its derived classes. Protected Friend — for the class, its descendants, and all classes in the assembly.
Is it possible to explicitly specify that a property is visible only to child classes outside the assembly but not within the assembly?
No, there is no such level. Protected Friend shares visibility between descendants and the assembly at the same time, but it is not possible to separate these areas.
If a method in the base class is defined as Protected, can it be overridden as Public in the derived class?
No, the access level can only be maintained or expanded downwards, but not narrowed; expanding access violates encapsulation principles. In .NET, the compiler will produce an error when attempting to narrow access.
A novice developer declared internal business logic methods as Public. After some time, during program updates, many bugs arose due to uncontrolled access to these methods by external components.
Pros:
Cons:
An experienced programmer uses Protected and Private, separating responsibilities between parent and child classes. As a result, updates do not affect external APIs, and the number of bugs is reduced.
Pros:
Cons: