CodeGym /Courses /JAVA 25 SELF /Access modifiers

Access modifiers

JAVA 25 SELF
Level 15, Lesson 1
Available

1. Overview of access modifiers

In Java there are four access levels for classes, fields, methods, and constructors:

Modifier Where is it accessible?
public
Everywhere: inside the class, in other classes, in other packages
protected
Inside the class, in subclasses (descendants), and in other classes of the same package
(package-private)
Only within the package (if no modifier is explicitly specified)
private
Only within the current class

Let’s break each of them down in more detail — with examples, jokes, and unexpected twists.

public — public access

public is like an announcement to the whole world: “Everyone is welcome!”. If a class, field, method, or constructor is declared public, it can be accessed from any other class, even from another package.

Example:

public class Cat {
    public String name;
    public void sayMeow() {
        System.out.println("Meow!");
    }
}

You can access this class and its fields/methods from anywhere. This is handy when you want your class to be available to everyone — for example, when you’re writing a library.

But! Public fields are not always a good idea (see the previous lecture). Typically, only methods that must be accessible from outside are made public, while fields are almost always kept private.

private — access only within the class

private is like a safe with a combination lock: nobody except the class itself can access those members. Even subclasses do not see private fields and methods!

Example:

public class Cat {
    private String secretName;

    public void setSecretName(String name) {
        secretName = name;
    }

    public String getSecretName() {
        return secretName;
    }
}

Here, secretName cannot be read or changed directly from another class. Only Cat itself (or its methods) can do that. This is the basis of encapsulation: we hide internal details and expose them only through methods.

protected — protected access

protected is like a VIP pass: access is granted to the class, its subclasses (even if they are in other packages), and all classes within the current package.

Example:

public class Animal {
    protected int age;

    protected void growOlder() {
        age++;
    }
}

Now any class that extends Animal can access the age field and the growOlder() method.

public class Cat extends Animal {
    public void haveBirthday() {
        growOlder();
        System.out.println("The cat turned " + age + " years old!");
    }
}

All classes within the same package also have access to protected members.

(package-private) — access within the package

If you don’t specify an access modifier at all, a class member is considered package-private (or “default access”). It’s like a door without a lock, but only for your own: access is granted only to classes from the same package.

Example:

class Dog {
    String name; // package-private
    void bark() { // package-private
        System.out.println("Woof!");
    }
}

The class Dog, its field name, and the method bark() are accessible only within the same package. Trying to access them from another package will cause a compilation error.

2. Applying modifiers to fields and methods

Why fields are almost always private

Class fields are its internal state. If you leave them public, any external code can change them at any time. It’s like letting random kids treat your furniture like Lego: one day you’ll wake up to find the fridge upside down in the bathroom.

Example of poor encapsulation:

public class Person {
    public String name;
    public int age;
}

Example of good encapsulation:

public class Person {
    private String name;
    private int age;

    public void setName(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }
}

Methods (getters and setters) let you control exactly how external classes can change fields. For example, you can forbid a negative age.

When to make methods public, protected, or package-private

  • public — if the method should be available to everyone. Usually this is the core functionality of the class.
  • protected — if the method is needed only by subclasses or within the package (e.g., helper methods that might be useful to child classes).
  • package-private — if the method is needed only within the package and should not be accessible from outside (e.g., internal implementation details).
  • private — if the method is used only inside the class itself (e.g., helper methods for internal logic).

Example:

public class BankAccount {
    private double balance;

    public void deposit(double amount) {
        if (amount > 0) {
            balance += amount;
        }
    }

    protected void applyInterest() {
        balance *= 1.05;
    }

    void internalAudit() {
        // package-private: only for classes within the package
    }

    private void logAction(String action) {
        // for the class's internal needs only
    }
}

3. Code examples: a class with different access levels

Let’s create a class that has it all: public, private, protected, and package members. We’ll also try to access them from other classes and see what happens.

package zoo;

public class Animal {
    public String publicName = "Available to everyone";
    protected String protectedName = "Only for subclasses and the package";
    String packageName = "Package only";
    private String privateName = "Only for Animal";

    public void publicMethod() {
        System.out.println("Public method");
    }

    protected void protectedMethod() {
        System.out.println("Protected method");
    }

    void packageMethod() {
        System.out.println("Package method");
    }

    private void privateMethod() {
        System.out.println("Private method");
    }
}

Now let’s try to access these members from another class in the same package:

package zoo;

public class Main {
    public static void main(String[] args) {
        Animal animal = new Animal();
        System.out.println(animal.publicName);      // OK
        System.out.println(animal.protectedName);   // OK
        System.out.println(animal.packageName);     // OK
        System.out.println(animal.privateName);  // Error: private
        animal.publicMethod();                      // OK
        animal.protectedMethod();                   // OK
        animal.packageMethod();                     // OK
        animal.privateMethod();                  // Error: private
    }
}

And now let’s try to access these members from another package:

package other;

import zoo.Animal;

public class Test {
    public static void main(String[] args) {
        Animal animal = new Animal();
        System.out.println(animal.publicName);      // OK
        System.out.println(animal.protectedName); // Error: protected
        System.out.println(animal.packageName);   // Error: package-private
        System.out.println(animal.privateName);   // Error: private
        animal.publicMethod();                      // OK
        animal.protectedMethod();                // Error: protected
        animal.packageMethod();                  // Error: package-private
        animal.privateMethod();                  // Error: private
    }
}

Summary:

  • public — accessible everywhere.
  • protected — accessible within the package and in subclasses (even from other packages, when accessed via inheritance).
  • package-private — only within the package.
  • private — only within the class.

4. Best practices: how to choose an access modifier

Minimize visibility

The less code can see your field or method, the better. Expose only what external code really needs. This is called the principle of least privilege.

  • Fields should almost always be private. Exceptions — only for true constants (public static final), but more on that in later lectures.
  • Make methods public only if they are part of the class’s external interface.
  • Helper methods (internal logic) — private.
  • Methods for subclasses — protected.
  • Internal service methods for the package — package-private.

Why does this matter?

  • Any change to implementation details can break other people’s code if those details are exposed.
  • The class becomes harder to test and maintain.
  • Accidental mistakes (e.g., changing a field incorrectly) can lead to bugs.

Sometimes beginners think: “Why bother with all this — let everything be public!” But later, as the project grows, they end up rewriting half the program because someone was changing class fields directly.

5. Common mistakes when working with access modifiers

Error No. 1: Left fields public or package-private by default.
If you don’t specify a modifier, a field or method will be accessible to all classes within the package. This can lead to surprises if someone starts changing your fields directly.

Error No. 2: Attempting to access a private member from another class.
The compiler won’t let you do that — you’ll get an error. And if you try to bypass it via reflection (reflective access) — welcome to a world of bugs and unexpected crashes.

Error No. 3: Too much public.
If you declare everything public, the class becomes like an open box of wires — anyone can tug the wrong wire and break everything.

Error No. 4: Not using protected for methods that are needed only by subclasses.
If a method is needed only for extension in child classes, declare it protected, not public.

Error No. 5: Implicit package-private visibility.
Sometimes people forget to specify a modifier, and the method becomes accessible to the entire package. This can be a surprise if you thought it was private.

1
Task
JAVA 25 SELF, level 15, lesson 1
Locked
Reading the name on a digital business card 🃏
Reading the name on a digital business card 🃏
1
Task
JAVA 25 SELF, level 15, lesson 1
Locked
Magic calculator with a secret mechanism ➕
Magic calculator with a secret mechanism ➕
1
Task
JAVA 25 SELF, level 15, lesson 1
Locked
Internal assistance within the development team 🤝
Internal assistance within the development team 🤝
1
Task
JAVA 25 SELF, level 15, lesson 1
Locked
Managing a digital library: who can do what 🏛️
Managing a digital library: who can do what 🏛️
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION