Unit 3 · OOP Concepts

3.3.1Access modifiers

Access modifiers are how a class protects itself. They decide which other code can see and use each attribute, method and constructor.

They control where a member can be accessed from.

ModifierSame classSame packageSubclass (other package)Anywhere
privateYesNoNoNo
default (no keyword)YesYesNoNo
protectedYesYesYesNo
publicYesYesYesYes
publicanywhereprotected+ subclasses in other packagesdefault (no keyword)same packageprivatesame class only
Access levels from most restrictive (private) to least restrictive (public)

Guideline: make attributes private, make the methods that other classes need public, and use protected for members that subclasses need.

Java
public class Account {
    private double balance;        // hidden
    public void deposit(double a)  // visible to all
    { balance += a; }
}

Account acc = new Account();
// acc.balance = 5000;   // ERROR: balance has private access in Account
acc.deposit(5000);       // correct

In C++ the same ideas exist as private:, protected: and public: sections. Python uses naming conventions (_name, __name) instead.

Packages: the meaning of "same package"

A package is a named group of related classes, similar to a folder. The first line of a file says which package its class belongs to:

Java
package school.records;     // this class is in the package school.records

public class Student { ... }

To use a public class from another package, you import it: import school.records.Student;. Packages keep large programs organised and stop name clashes, because two classes can have the same name if they are in different packages. If a file has no package line, its class is in the default package. Small examples, like the ones in this module, often do this.

Each level in detail

Modifiers on a class

A top-level class can only be public or default. A public class must be saved in a file with the same name. A class can never be private unless it is declared inside another class.

Choosing the right level

Start with the most restrictive level that works, and only open it up when you have a reason. It is easy to make something more visible later, but making a public member private can break every class that already uses it.

MemberUsual choice
Attributesprivate (with getters/setters where needed)
Methods other classes should callpublic
Helper methods used only inside the classprivate
Members a subclass needs to use or overrideprotected
Constants such as MAX_SIZEpublic static final is fine, because they cannot be changed

Common mistake: making every attribute public "so it is easy to use". It works until someone sets balance = -5000 or age = -3, and then there is no single place to add a check. Use private attributes and methods that validate their input.

Test yourself with the quiz below: every combination of modifier and location is mixed at random.