J O S E P H J O S E P H

Java Access Modifiers

Classes, Attributes and Methods

public

Accessible by any other class.

// Class
public class Example {}

// Attribute
public String access = "Public";

// Method
public void printStr(String str) {
  System.out.println(str);
}

private

Accessible only within the same class. Available on members of a class only, not on the class itself. Best practice: make members private as much as possible.

// Attribute
private String access = "Private";

// Method
private void printStr(String str) {
  System.out.println(str);
}

protected

Accessible only within the same package AND subclasses that may be in a different package. Available on members of a class only, not on the class itself.

// Attribute
protected String access = "Protected";

// Method
protected void printStr(String str) {
  System.out.println(str);
}

default

Accessible only by classes in the same package. This is used when an explicit access modifier is not specified. Best practice: avoid using default access.

// Class
class Example {}

// Attribute
String access = "Default";

// Method
void printStr(String str) {
  System.out.println(str);
}