Basic Syntax

Access Control

🙋 Need help? Ask an expert now!

In Java, access control tells the program how much access a variable, class or method is given. Access control is important because it affects visibility based on different access control types. You may have noticed in prior topics the use of words such as public and private, which are examples of access control types. Take a look at the examples below.
package exlcode;

public class AccessControlExample {

  public static void main(String[] args) {
    // This will be explained in Unit 8
    AccessControlTest accessControlTest = new AccessControlTest();
    // accessControlTest.exampleVariableThree will cause an error because
    // exampleVariableThree is private
package exlcode;

public class AccessControlTest {

  public static int exampleVariableOne = 5;
  public static int exampleVariableTwo = 10;
  private static int exampleVariableThree = 100;

When a variable's or method's access is not specified public or private, it will have default visibility. Default visibility is packaged private; it is visible to all classes in the same package. It is best to declare members public if that is the true intent. If an instance variable is declared private, it can only be used by the methods of that class. In the preceding example, AccessControlTest has its own private variable that is not accessible by the main method of the AccessControlExample class.

Access control allows other users to use your program without ever accessing, altering, or even knowing that the private variables or methods exist.

Edit Me on GitHub!

Application Question

Which methods and fields shown below can only be accessed by its own class?