Course Content
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.
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.
Thanks for your feedback!