Skip to main content

Access Modifiers

Access modifiers control who can see and use your variables and methods.

The Three Main Types

public class Robot {
public String name; // Any class can access
private DcMotor motor; // Only this class can access
protected double speed; // This class and subclasses can access
}

Public

Everyone can access it:

public void moveForward() {
// Other classes can call this method
}

Robot myRobot = new Robot();
myRobot.moveForward(); // This method can get called from any other class

Private

Only the same class can access it:

private DcMotor leftMotor;

private void calibrateMotors() {
// Only methods in this class can call this
}

// myRobot.calibrateMotors(); // This won't work from outside the class

Protected

Same class and subclasses can access it:

protected double maxSpeed = 1.0;

// Useful when one class extends another
public class AdvancedRobot extends Robot {
public void turbo() {
maxSpeed = 1.5; // Can access parent's protected variables
}
}

Quick Reference

ModifierWho Can AccessWhen to Use
publicEveryoneMethods others should call, constants
privateOnly this classInternal details, helper methods
protectedThis class + subclassesShared with child classes