Conteúdo do Curso
Java Extended
Java Extended
Access modifiers
Access modifiers in Java are keywords that determine the accessibility of classes, variables, methods, and constructors. Here's a brief explanation of the four access modifiers:
Public
The public
modifier allows unrestricted access to the class, variable, method, or constructor. It can be accessed from anywhere in the program, even from outside the class and in other packages;
Private
The private
modifier restricts access to only within the same class. It ensures that the member is not accessible from any other class, including subclasses and other packages;
Protected
The protected
modifier allows access within the same class, subclasses, and other classes in the same package. It provides a level of access that is more restrictive than public but less restrictive than private;
Package-private
If the access modifier is not specified, it is considered the default access level. The default modifier allows access within the same package but restricts access from outside the package.
Note
There's no need to be afraid of the terms constructor, package, and subclasses. We will learn what they are, how to create them, and how to use them later if this and future courses.
Let's talk about imports. Access modifiers primarily determine where they can be imported into the program. Let's take a look at the table that shows where access can be gained to a field/method/class marked with a specific access modifier:
Let's go through each access modifier in more detail:
public
- with this access modifier, you can access the object from anywhere;protected
- you can access objects with this access modifier from the class in which the object is located, from the package in which the file with this class is located, and from subclasses (we will explore these topics in more detail in a separate course);package private
or default - you can access objects with this access modifier from the class in which the object is located and from the package in which the file with this class is located;private
- you can only access objects with this access modifier from the class in which the object is instantiated.
Note
All these access modifiers are part of the object-oriented programming (OOP) principle called encapsulation. We will explore all the principles of OOP and discuss access modifiers in more detail in a separate course.
Obrigado pelo seu feedback!