Access Modifiers:

Access modifiersare the keywords which controls the accessibility of classes, methods, fields or other members in a program.

Public:

The public members are accessible everywhere.

helloworld.java
public class MyClass {
    public int publicField;
    public void publicMethod() {
        // Code here
    }
}


Private:

The private members are accessible only within their own class.

helloworld.java
public class MyClass {
    private int privateField;
    private void privateMethod() {
        // Code here
    }
}

Protected:

The protected members are accessible are accessible within the same class, subclasses, and within the same package. They are not accessible from outside the package if there is no inheritance relationship.

helloworld.java
public class MyClass {
    protected int protectedField;
    protected void protectedMethod() {
        // Code here
    }
}

Default (Package-Private):

When no access modifier is specified (i.e., no public, private, or protected keyword), the member has "package-private" or "default" access. Members with the default access are accessible only within the same package.

helloworld.java
class MyClass {
    int defaultField;
    void defaultMethod() {
        // Code here
    }
}

Some Special Modifiers in Java:

In addition to access modifiers, java also has a few special modifiers:

  • Static (static) : Used to declare class-level members (fields and methods) that belong to the class itself rather than to instances of the class.
  • Final (final) : Used to make a member (field, method, or class) unchangeable or prevent method overriding (for methods) or class extension (for classes).
  • Abstract (abstract) : Used with classes to declare abstract classes, which cannot be instantiated and may have abstract methods (methods without implementations). Abstract methods are meant to be implemented by subclasses.
  • Transitive (transient) : Used with fields to indicate that they should not be serialized when an object is serialized. It is used for managing object persistence.
  • Volatile (volatile) : Used with fields to indicate that they may be modified by multiple threads, ensuring proper synchronization when accessing the field.

Access modifiers play a vital role in encapsulation and maintaining the security and integrity of your Java code. They allow you to manage the accessibility of class members, controlling which parts of your classes can be accessed and modified. This practice is fundamental in adhering to sound object-oriented programming principles.