Contenido del Curso
C# Beyond Basics
C# Beyond Basics
Common Access Modifiers
You might already be familiar with the keyword public
. It is an access modifier which defines where a certain class, method or a field can be accessed from.
Similarly there are terms like private
and protected
. Both of these terms can be used to specify the accessibility of a method or a field.
When we write public
before a class, it simply makes the class accessible from different parts (files) of the program. We don't need to explore that aspect in detail as it is out of the scope of this chapter.
When we specify a method or a field as public
, we basically make that property of the class accessible from anywhere inside the code through an object:
index
If we don't want a field or a method of an object to be accessible outside the class, we can simply make it private
:
index
It is important to note that the private fields and methods are not inherited by the derived classes:
index
To make a field or method inaccessible from outside the class but accessible from child classes, we use the protected
keyword:
index
Sometimes, to be able to access private attributes from a class we create public methods called getters. The method getMagnitude
is an example of a getter. This ensures that the field is only readable and not writable, making that attribute read-only.
Note: If no access modifier is specified to a class member, it is assumed to be private
by default.
¿Todo estuvo claro?