OBJECT-ORIENTED PROGRAMMING

Java access modifiers

Access modifiers ( access modifiers) determine which parts of a program can use a class, attribute, method or constructor. They protect internal object state and clearly define a class's public interface.

Two groups of modifiers

  • Access modifiers control where code is accessible: public, private and protected.
  • Other modifiers provide other behavior, for example, , final or abstract.

This lesson focuses specifically on access levels.

Access to top-level classes

A top-level class can have public or package access by omitting the modifier:

Java top-level class access
AccessAccessibility
publicFrom any package, provided the class is properly imported
Package accessOnly within the same package; no modifier is written
// File: Knyga.java
public class Knyga {
    // The class is also accessible from other packages
}

// No modifier specified – package access
class KnygosPagalbininkas {
    // The class is accessible only within the same package
}
There is no console output.

These are only two class declarations. Neither class has a main() or println().

  1. public class Knyga can also be used from other packages.
  2. A public class's filename must match its class name: Knyga.java.
  3. For KnygosPagalbininkas , no access modifier is written.
  4. This class therefore has package access and can only be used by code in the same package.
default is not a keyword written here.

“Default access” means that no access modifier is specified.

Access to attributes, methods and constructors

Java class member access levels
ModifierSame classSame packageSubclass in another packageOther classes in another package
private✅ Yes❌ No❌ No❌ No
(default)✅ Yes✅ Yes❌ No❌ No
protected✅ Yes✅ Yes✅ Yes*❌ No
public✅ Yes✅ Yes✅ Yes✅ Yes
* protected access from another package has an additional rule.

A subclass accesses the member through inheritance: through itself or an instance of its own subclass. It cannot access a protected member through an arbitrary, separately obtained superclass object.

public and private example

A public book title is accessible from outside, but the read page count is kept within the class. External code obtains it through a public method:

class Knyga {
    public String pavadinimas = "Mažasis princas";
    private int perskaitytaPuslapiu = 40;

    public int gautiPerskaitytusPuslapius() {
        return perskaitytaPuslapiu;
    }
}

public class Main {
    public static void main(String[] args) {
        Knyga knyga = new Knyga();

        System.out.println(knyga.pavadinimas);
        System.out.println(knyga.gautiPerskaitytusPuslapius());
    }
}
Console output

Mažasis princas
40

  1. The attribute pavadinimas is marked public, so Main accesses it directly.
  2. The attribute perskaitytaPuslapiu is marked private, so it cannot be accessed directly from outside.
  3. The public method gautiPerskaitytusPuslapius() runs inside the class itself and can read the private attribute.
  4. Main calls this method and safely obtains the number 40.

Direct use of the private attribute would look like this:

Knyga knyga = new Knyga();

System.out.println(knyga.perskaitytaPuslapiu);
Compiler result

error: perskaitytaPuslapiu has private access in Knyga

  1. The code tries to access knyga.perskaitytaPuslapiu from outside the Knyga class itself.
  2. Modifier private allows the field to be used only within the class.
  3. The compiler rejects the program, so this incorrect fragment produces no console output.
  4. The correct approach is to use the public method provided by the class.

Package access

With no modifier, a class member is accessible only within its package. This is useful for internal module details that need not be exposed to the whole program.

package lt.pavyzdys.knygos;

class KnygosPagalbininkas {
    int puslapiuSkaicius = 96;

    void rodytiPuslapius() {
        System.out.println("Puslapių: " + puslapiuSkaicius);
    }
}

public class Main {
    public static void main(String[] args) {
        KnygosPagalbininkas pagalbininkas = new KnygosPagalbininkas();
        pagalbininkas.rodytiPuslapius();
    }
}
Console output

Puslapių: 96

  1. Both classes belong to the same package, lt.pavyzdys.knygos.
  2. For KnygosPagalbininkas, its attribute and its method have no modifier.
  3. This means all of them are accessible within the same package.
  4. Main creates a helper object and calls its method.
  5. If Main were in another package, this use would not be allowed.

What does protected actually allow?

protected is easiest to understand as two permissions combined. Any class in the same package can use the member. A subclass can also use it through inheritance, even from another package.

The key idea

protected does not mean “accessible everywhere”. In another package, it specifically grants additional access to a subclass through inheritance.

The following classes are deliberately placed in two different packages. If they shared a package, the example would not show the key distinction of protected access:

// File: biblioteka/Leidinys.java
package biblioteka;

public class Leidinys {
    protected String pavadinimas = "Mažasis princas";

    protected void rodytiPavadinima() {
        System.out.println(pavadinimas);
    }
}

// File: parduotuve/Knyga.java
package parduotuve;

import biblioteka.Leidinys;

public class Knyga extends Leidinys {
    public void rodytiInformacija() {
        // Allowed because Knyga extends Leidinys
        this.rodytiPavadinima();
        System.out.println(this.pavadinimas);
        System.out.println("Tai yra knyga");
    }

    public static void main(String[] args) {
        Knyga knyga = new Knyga();
        knyga.rodytiInformacija();

        // Not allowed: in another package, a protected member
        // cannot be accessed through a plain Leidinys object.
        // Leidinys leidinys = new Leidinys();
        // leidinys.rodytiPavadinima();
    }
}
Console output

Mažasis princas
Mažasis princas
Tai yra knyga

  1. Leidinys is in the package biblioteka. It has the protected attribute pavadinimas and the method rodytiPavadinima().
  2. Knyga is in another package, parduotuve, so the same-package rule alone does not help it.
  3. Knyga extends Leidinys makes the Knyga class a Leidinys subclass.
  4. Through inheritance, inside Knyga you can write this.rodytiPavadinima() and this.pavadinimas.
  5. The first line comes from the inherited method, the second from directly reading the inherited attribute, and the third from Knyga class itself.
  6. However, Knyga cannot create an ordinary Leidinys object and use it to access the protected method. The commented lines would cause compilation errors.
How would the member modifier change this example?
ModifierCould Knyga use the member from another package?Why?
private❌ NoThe member is directly accessible only within the Leidinys class.
Default access❌ NoKnyga is in another package.
protected✅ Yes, through inheritanceKnyga is Leidinys subclass.
public✅ YesA public member is accessible without a special subclass exception.
A short rule to remember

private – class only; default access – package; protected – package and subclasses; public – everywhere.

Restricting constructor access

An access modifier can also control who may create instances of a class:

public class BibliotekosInformacija {
    private BibliotekosInformacija() {
        // Objects cannot be created from outside the class
    }

    public static void rodytiPavadinima() {
        System.out.println("Miesto biblioteka");
    }

    public static void main(String[] args) {
        BibliotekosInformacija.rodytiPavadinima();
    }
}
Console output

Miesto biblioteka

  1. The class constructor is marked private, so other classes cannot write new BibliotekosInformacija().
  2. However, the public static method belongs to the class itself and needs no object.
  3. The method is called through the class name, BibliotekosInformacija.rodytiPavadinima().
  4. This approach suits utility classes that provide only static operations or control their own object creation.

Which access level should you choose?

  • Start with the narrowest access needed.
  • Usually mark internal object attributes private.
  • public Reserve this for the deliberately designed class interface:
  • protected Use this only when inheriting classes genuinely need access to the member:
  • Package access suits internal cooperation between related classes in the same package.