Access Modifiers in Java

Modifiers are keywords that stand in the definition of classes, methods, or variables and define them more closely. In Java, we use several access modifiers to determine access levels to a class, method, or variable.

There are four types of Java access modifiers:

  • Default
  • Private
  • Public
  • Protected

1. Default access modifier

If we do not put a modifier in the declaration, the method or variable will be visible in all classes at the package level.

// declaration of variables without modifiers 
String s = "Hello World!";
int i = 5;
// method without a modifier, it can be accessed at the package level
int sum(int a, int b){
  return a + b;
}

2. Private access modifier

The methods or variables declared with a private modifier are visible only within the class in which they are defined, meaning that they cannot be accessed from another class.

Classes and interfaces cannot be private.

public class Car {
    
  // private fields
  private String color;
  private int speed;
 
  // ...
}

3. Public access modifier

Classes, methods, or variables declared with a public modifier can be accessed from any class in the application.

public class Car {
    
  // fields and methods are public and they can be accessed from any class
  public String color;
  public int speed;
 
  public void start() {
    // ...
  }
    
  // main() is always public
  public static void main (String[] arguments){
    // ...
  }
}

4. Protected access modifier

The methods or variables that are declared with protected access modifier are visible within the class in which they are defined, in the subclasses derived (inherited) from that class and within the package.

class Car {
   
  protected String getMaxSpeed() {
    // ...
  }
}

Rules to remember:

  • Methods declared public in the superclass must also be public in all subclasses.
  • Methods declared protected in a superclass must be protected or public inside the subclasses. It can’t be private.

That’s it!

 

Leave a Reply

Your email address will not be published.