← Back to Week 5

Default Access Modifier

When you write a field or method with no access keyword, Java doesn't make it public or private — it gets a fourth, lesser-known level called package-private.

The 4 Java Access Levels
Modifier Keyword you write Same class Same package Other package
public public String name;
protected protected String name; subclasses only
(default) String name; — no keyword
private private String name;
package com.pluralsight.hotel;
✅ Same package — access works
Room.java — in com.pluralsight.hotel
public class Room {
  // no keyword = package-private
  String number;
  int beds;
}
RoomBooker.java — in com.pluralsight.hotel
public class RoomBooker {
  public void book() {
    Room r = new Room();
    r.number = "101";  works — same package 
    r.beds = 2; works 
  }
}
package com.pluralsight.frontdesk;
❌ Other package — blocked
CheckIn.java — in com.pluralsight.frontdesk
import com.pluralsight.hotel.Room;

public class CheckIn {
  public void go() {
    Room r = new Room();
    r.number = "101";  ERROR — not visible 
    r.beds = 2; ERROR 
  }
}
Even though both classes import the same Room, the package-private fields are off-limits from outside com.pluralsight.hotel.
Best practice: Write private explicitly on every field, and public on every method that needs to be called from outside. Don't rely on the default — it makes your intent unclear and accidentally exposes data to anything in the same package. The workbook calls this out in its example: "In this course we will use access modifiers for all members and functions." The default exists, but you almost never want it on purpose.
← Boolean Getters Cohesion & Coupling →