Skip to lesson
MentorNxt home

Java Programming

Packages, Imports & Access Control

Access modifiers: public, private and default

An access modifier is a word like public or private in front of a class, field or method. It decides which other classes are allowed to use it.

Who can use this?

No other class should be able to set a wallet balance to -1000. An access modifier, a word like public or private in front of a field or method, decides which classes may use it, and javac checks the rule.

Java
class Wallet {    private static int balance = 500;   // only Wallet can use it
    public static int getBalance() {    // any class can call it        return balance;    }}

balance is a field: a variable inside the class but outside every method. With static it belongs to the class, just like a static method. The fields and methods of a class are its members.

The four access levels

Java has four levels, from most open to most closed. The picture shows who may use a member at each level.

Who can use a member. public: same class yes, same package yes, other package yes. protected: yes, yes, and in another package only child classes. default (no word): yes, yes, no. private: yes, no, no.
protected matters only with inheritance, which the OOP section covers. In this module you need public, default and private.

Default: same package only

FeeCalculator has a field lateFine with no modifier in front. No word means default access (also called package-private): every class in the same package may use it, and no class outside.

Example 1 · Default access inside one package

FeeCalculator.javaJava
// File: src/com/college/fees/FeeCalculator.javapackage com.college.fees;
public class FeeCalculator {    static int lateFine = 100;
    public static int total(int fee, int daysLate) {        return fee + daysLate * lateFine;    }}
// File: src/com/college/fees/FineCheck.javapackage com.college.fees;
public class FineCheck {    public static void main(String[] args) {        System.out.println("Fine per day: " + FeeCalculator.lateFine);        System.out.println("Fee, 3 days late: " + FeeCalculator.total(45000, 3));    }}
Sample output
Fine per day: 100
Fee, 3 days late: 45300

What this code does

  • static int lateFine has no modifier, so it has default access.
  • FineCheck is in the same package, com.college.fees, so it can read FeeCalculator.lateFine directly.

Example 2 · Default access from another package

Main.javaJava
// File: src/com/college/app/Main.javapackage com.college.app;
import com.college.fees.FeeCalculator;
public class Main {    public static void main(String[] args) {        System.out.println(FeeCalculator.total(45000, 3));        System.out.println(FeeCalculator.lateFine);    }}
Sample compiler output
src/com/college/app/Main.java:9: error: lateFine is not public in FeeCalculator; cannot be accessed from outside package
        System.out.println(FeeCalculator.lateFine);
                                        ^
1 error

What this code does

  • Main is in com.college.app, a different package, so the default field lateFine is hidden from it.
  • Line 8 is fine, because total is public. Only line 9 fails.

private keeps data safe

If balance were public, any class could set it to -1000. Make the field private, and give public methods that check every change before they make it.

Example 3 · A private field with public methods

WalletApp.javaJava
class Wallet {    private static int balance = 500;
    public static void add(int amount) {        if (amount > 0) {            balance = balance + amount;        } else {            System.out.println("Invalid amount: " + amount);        }    }
    public static int getBalance() {        return balance;    }}
public class WalletApp {    public static void main(String[] args) {        Wallet.add(200);        Wallet.add(-1000);        System.out.println("Balance: " + Wallet.getBalance());    }}
Output
Invalid amount: -1000
Balance: 700

What this code does

  • balance is private, so only code inside Wallet can change it.
  • WalletApp has to go through add, and add refuses -1000: 500 + 200 = 700 is the only change.
  • Both classes are in one file; only WalletApp is public, so the file is WalletApp.java.

Example 4 · Using a private field from outside

WalletApp.javaJava
class Wallet {    private static int balance = 500;
    public static int getBalance() {        return balance;    }}
public class WalletApp {    public static void main(String[] args) {        Wallet.balance = -1000;        System.out.println(Wallet.getBalance());    }}
Sample compiler output
WalletApp.java:11: error: balance has private access in Wallet
        Wallet.balance = -1000;
              ^
1 error

What this code does

  • Line 11 is in WalletApp, but balance is private to Wallet, so javac stops the build.
  • Fix: call a public method of Wallet instead of touching the field.
A good habit: make fields private, and make a method public only when other classes need it.

Rules for classes

A top-level class (one that is not inside another class) can only be public or default. A default class is hidden outside its package, even when its methods are public.

Topper.javaJava
public class Topper { }    // any package can use itclass Helper { }           // only this packageprivate class Secret { }   // error: modifier private not allowed here

A public class must be saved in a file with the same name, as in Your first Java program (opens in a new tab).

Classify

Compiles or error?

Tap a line of code, then say whether javac accepts it.

Next step

Check your understanding

9 quick questions