When private doesn’t quite mean what you think it means, Java edition

Alonso Del Arte
3 min readJun 17, 2024
Photo by Pierre Bamin on Unsplash

Private access in Java is about regulating scope at compile time, not enforcing security measures at runtime. When something is declared private in a particular Java class, it is not accessible to other Java classes.

Well, we should qualify that regarding nested classes, and we will. Consider this toy example of a class:

package com.example;

public class ToyExample {

private int counter = 0;

}

Then a ToyExample instance’s counter can’t be accessed by any other class.

package com.example;

import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;

class ToyExampleTest {

@Test
void testCounter() {
ToyExample instance = new ToyExample();
instance.counter = 1; // ERROR!!! This will not compile
}

}

But whatever is private in an inner or nested static class is still accessible in the containing class.

package draft.com.example;

public class ToyExample {

private int counter = 0;

public static void main(String[] args) {
NestedClass instance = new NestedClass();
instance.innerCounter++; // Not a syntax error
}

static class NestedClass {

private int innerCounter = 0…

--

--

Alonso Del Arte

is a Java and Scala developer from Detroit, Michigan. AWS Cloud Practitioner Foundational certified