In this Java Tutorial, you will learn what access modifiers are in Java, how modifiers are helpful in controlling the access to a class or members of a class.

Access Modifiers in Java

There are two types in access modifiers

  1. Class Level Modifiers – These modifiers control access to a class.
    • public
    • default
  2. Class-Member Level Modifiers – These modifiers control access to the members of a class: methods and properties.
    • public
    • private
    • protected
    • default

Class Level Modifiers

The syntax to specify a modifier for Class is as shown below.

</>
Copy
modifier class ClassName{ ... }
modifiercould be public / default
classis the standard keyword to define a class
ClassName is the name of the class

1. public – Class Level Modifier

The modifier, public, makes the class visible/accessible to the classes everywhere. A sample code snippet to make a class, which is accessible to public, is shown below:

</>
Copy
public class MyClass{
    ...
}

2. default – Class Level Modifier

By default, if no modifier is given to a class, its visible only to the classes present in same package as that of the class. A sample code snippet to make a class, which is accessible by default only to classes in the same path as of itself, is shown below:

</>
Copy
class MyClass{
    ...
}

Diagrammatic Representation of Class Modifiers in Java

The following diagram depicts the public, default accessibility of SampleClass.java.