course content

Course Content

Introduction to Java

Access ModifiersAccess Modifiers

When declaring a class in Java, you can use access specifiers to protect both the variables and the methods of the class. The Java language supports four access levels: private, protected, public, and default.

Let's take a closer look at each access level.

Private

Private is the access level with the most limitations. Only members of the class in which it is defined have access to a private member. Declare any members that should only be used by the class using this access modifier. Private members are similar to secrets you'd never share with anyone. Use the private keyword in a member's declaration to make it private.

For example:

java

Main.java

We are attempting to access the Information class's private variable from the Main class, which causes the error to be raised.

Public

The public is the most straightforward access modifier. The public members of a class are accessible to all classes in all packages. Declare public members only if others using them won't result in undesirable outcomes. There is no private or family information hidden here. Use the keyword public to declare a member as public.

For example:

java

Main.java

Protected

The protected modifier is all classes in the same package that can access the members. Use the protected access level when it is appropriate for a class's subclasses to have access to a member but not for unrelated classes. Use the keyword protected to identify a protected member.

For example:

java

Main.java

Default

The default access modifier is assumed if we do not explicitly specify an access modifier for classes, methods, variables, etc. Classes in the same package can access the members in the default modifier. This access is based on the idea that classes in the same package are reliable associates.

For example:

java

Main.java

Here, the default access modifier belongs to the Blogger class. Additionally, all classes included in the defaultAccess package can see this class. However, a compilation error will occur if we attempt to use the Blogger class in a class that is not part of defaultAccess.

1. Which access modifier can restrict class members to get inherited?
2. Which access modifier allows members of one class to access members of another class within the same package?

question-icon

Which access modifier can restrict class members to get inherited?

Select the correct answer

question-icon

Which access modifier allows members of one class to access members of another class within the same package?

Select the correct answer

Section 2.

Chapter 4