Access Modifiers
Access Modifiers in Java
Every field, method and constructor you write can be used by some code and hidden from other code. Java decides which at compile time, from the declaration's access level. You meet this the first time you write a class with fields, and you use it in every class after that. This lesson covers the four access levels, how to read them in code, and how to choose one when you design a class.
The four access levels
An access modifier is a keyword placed before a declaration that sets which classes may refer to that member by name. Java has three of these keywords, public, protected and private. A fourth level, called package-private access and often called default access, applies when you write none of them. Leaving out the keyword does not make a member private: every class in the same package can still use it.
The table covers fields and methods in ordinary classes, assuming the declaring class is accessible. Protected constructors have different access restrictions.
Modifier | Same class | Same package | Subclass in another package | Any other class |
|---|---|---|---|---|
public | yes | yes | yes | yes |
protected | yes | yes | yes, with the restrictions below | no |
none (package-private) | yes | yes | no | no |
private | yes | no | no | no |
Read the table from the bottom row up. Each level keeps the permissions of the level below it and adds more access, so the four levels nest inside one another. A protected field or method is open to its whole package and allows inherited access from subclasses elsewhere.
Outside the declaring package, protected access must occur within a subclass's body. For an instance field or method, access through this or super is allowed; access through another reference requires its compile-time type to be that accessing subclass or a subclass of it. For example, inside SavingsAccount extends Account in another package, other.monthlyFee compiles when other is declared as SavingsAccount. It fails when other is declared as Account, even if the object is a SavingsAccount.
Reading access in code
The following example has a class in package bank and a class in a different package that tries to use it.
package bank;
public class Account {
private double balance;
String branchCode; // package-private
protected double monthlyFee;
public Account(double opening) { balance = opening; }
public double getBalance() { return balance; }
}package app;
import bank.Account;
public class Main {
public static void main(String[] args) {
Account a = new Account(50.0); // compiles: public constructor
System.out.println(a.getBalance()); // compiles: public method
a.balance = 1000.0; // error: private
a.branchCode = "X1"; // error: package-private, other package
a.monthlyFee = 0.0; // error: protected, Main is not a subclass
}
}The compiler checks every use of a member name against the member's modifier and the location of the code that uses it. Main is in package app and does not extend Account, so it falls in the last column of the table, where only public members are open. The constructor call and getBalance() compile. The compiler rejects all three field assignments. An access violation is a compile error, not a run-time error, so a program that contains one never runs.
Choosing a modifier
A practical rule is to give each member the most restrictive level that still lets the code that needs it compile. In a typical class, that rule leads to these choices:
- Fields: private, so other classes reach the data only through methods the class chooses to offer.
- Constructors and methods that other classes are meant to call: public.
- Helper methods used only by the class's own code: private.
- Members that subclasses are meant to use or override: protected.
A top-level class can only be public or package-private. A public class must be saved in a file with the same name, such as Account.java.
What to remember
- From widest to narrowest reach, the levels are public, protected, package-private (no keyword) and private.
- Writing no modifier gives package-private access, not private access.
- protected allows same-package access and inherited subclass access elsewhere. Cross-package instance access through another reference requires the accessing subclass's type or a subtype, not a superclass-typed reference.
- private restricts a member to code in its own class, for every object of that class.
- Breaking an access rule is a compile error.
- Choose the most restrictive level that still works.
Example: Which Student members can each class reach?
A school's software declares this class in package school:
package school;
public class Student {
private int id;
int gradeLevel;
protected double gpa;
public String name;
private boolean isHonours() {
return gpa >= 3.5;
}
public boolean differentStudent(Student other) {
return id != other.id;
}
}Three other classes use it: Registrar in package school, Tutor in package services, and GradStudent extends Student in package grad. Registrar and Tutor hold a reference s of type Student. GradStudent uses the members it inherits.
a) Which of the four fields id, gradeLevel, gpa and name can code in Registrar read through s?
Registrar is in the same package as Student but is not a subclass, so check each field against the same-package column of the access table.
- id is private, so for Registrar it is ________.
- gradeLevel has no modifier. Package-private access covers the same package, so it is ________.
- gpa is protected, and protected access includes the whole package, so it is accessible.
- name is public, so it is accessible.
Registrar can read three fields: gradeLevel, gpa and name. Only id is hidden from it.
b) Which of the four fields can Tutor read through s, and can it call s.isHonours()?
Tutor is in a different package and does not extend Student, so it falls in the any-other-class column, where only public members are open.
- id is private, so it is ________.
- gradeLevel is package-private, and services is a different package, so it is ________.
- gpa is protected, but Tutor is not a subclass, so it is ________.
- name is public, so it is accessible.
The method isHonours() is private, so the call s.isHonours() is a compile error. Tutor can read only name and cannot call isHonours().
c) Inside a method of GradStudent, which of the four fields can the code use as members inherited by the GradStudent object itself, such as this.gpa?
GradStudent is a subclass in another package. For such a class, the access table opens protected and public members, used through the subclass's own object.
- id is private, so it is not accessible. The field still exists inside every GradStudent object, but only code written in Student can name it.
- gradeLevel is package-private, and grad is a different package, so it is ________. Being a subclass does not help.
- gpa is protected, so it is ________.
- name is public, so it is accessible.
GradStudent can use gpa and name. Reading gpa through some other plain Student reference from package grad is a stricter case that Java does not allow; this part uses only the inherited field on the subclass's own object.
d) The method differentStudent reads other.id, which is the private field of a different Student object. Does Student compile?
Java grants private access to code written in the declaring class, whichever object the field belongs to. The expression other.id appears inside differentStudent, which is in the ________ that declares id, so the access is legal.
Yes, Student compiles. The same expression other.id written inside Registrar would be a compile error, because there it would be outside the declaring class.
A Java class member can carry one of four access levels. Arrange them from the most restrictive (the smallest set of code that may refer to the member) to the least restrictive (the largest set).
1.
protected
2.
private
3.
public
4.
package-private (no modifier)
The class Sensor is declared public in package lab and has these four members:
private int reading;
double offset;
protected void calibrate() { reading = 0; }
public double getReading() { return reading + offset; }Three other classes use Sensor. Logger is in package lab and does not extend Sensor. TempSensor extends Sensor is in package devices and uses only the members it inherits on its own object. Dashboard is in package ui and does not extend Sensor. In each cell, type yes if that class can refer to that member, or no if the reference is a compile error.
| Member | Logger (same package) | TempSensor (subclass, other package) | Dashboard (other package) |
| reading | |||
| offset | |||
| calibrate() | |||
| getReading() |