Contenido del Curso
Java OOP
Java OOP
OOP Principles: Encapsulation
Encapsulation
Another fundamental principle of Object-Oriented Programming (OOP). Probably the most crucial principle as the entire OOP paradigm relies on it. You have already encountered this principle in this chapter when designating fields and methods as private
or public
. But now we will discuss this principle in more detail.
Note
Please do not confuse the word 'interface' (a template for creation, a pattern) with the Interface that we will be studying in the next section!
Access modifiers
Access modifiers are an integral part of encapsulation, so even though we have discussed them before, we need to review this material. Below is the definition of access modifiers along with a table and a brief description:
-
public
: Members withpublic
access modifier are accessible from anywhere in the code. They have the widest scope. For example, apublic
method can be called from any class; -
private
: Members withprivate
access modifier are only accessible within the class where they are declared. They are not visible to external classes. This provides strong encapsulation; -
protected
: Members withprotected
access modifier are accessible within the same package and by subclasses, even if they are in different packages. This allows controlled sharing of information; -
default (package-private): If no access modifier is specified, the member is accessible only within the same package. It's a default level of access.
Let's see how access modifiers work in practice. There are two classes: one created in the same package as the main
class, and the other created in a different package. Let's see how access modifiers affect this:
In the screenshots, you can see where variables with corresponding names are accessible from.
I will also remind you that if you want to bypass access modifiers, you can read about it here: link.
Note
It's also worth mentioning that methods can also have access modifiers. They work in the same way as with fields. For example, a method with a private access modifier will only be accessible in the class where it was created.
Summary
Encapsulation is very helpful when data needs to be organized in compartments, making the code highly structured. Additionally, thanks to encapsulation, you can configure where and how your fields and methods can be accessed.
¡Gracias por tus comentarios!