JavaModifiers
Modifiers
By now, you are quite familiar with thepublic keyword that appears in almost all of our examples:
public class MainThepublic keyword is anaccess modifier, meaning that it is used to set the access level for classes, attributes, methods and constructors.
We divide modifiers into two groups:
- Access Modifiers - controls the access level
- Non-Access Modifiers - do not control access level, but provides other functionality
Access Modifiers
Forclasses, you can use eitherpublic ordefault:
| Modifier | Description | Try it |
|---|---|---|
public | The class is accessible by any other class | Try it » |
| default | The class is only accessible by classes in the same package. This is used when you don't specify a modifier. You will learn more about packages in thePackages chapter | Try it » |
Forattributes, methods and constructors, you can use the one of the following:
| Modifier | Description | Try it |
|---|---|---|
public | The code is accessible for all classes | Try it » |
private | The code is only accessible within the declared class | Try it » |
| default | The code is only accessible in the same package. This is used when you don't specify a modifier. You will learn more about packages in thePackages chapter | Try it » |
protected | The code is accessible in the same package andsubclasses. You will learn more about subclasses and superclasses in theInheritance chapter | Try it » |
Public vs. Private Example
In the example below, the class has onepublic attribute and oneprivate attribute.
Think of it like real life:
public- a public park, everyone can enterprivate- your house key, only you can use it
Example
class Person { public String name = "John"; // Public - accessible everywhere private int age = 30; // Private - only accessible inside this class}public class Main { public static void main(String[] args) { Person p = new Person(); System.out.println(p.name); // Works fine System.out.println(p.age); // Error: age has private access in Person }}Example explained
Here,name is declared aspublic, so it can be accessed from outside thePerson class. Butage is declared asprivate, so it can only be used inside thePerson class.

