TheWurstToplaner
TheWurstToplaner

Reputation: 5

Java: Why can i read a private attribute?

this might be a dumb question, but I was wondering why I can still read the radius and age attributes even though I used the private modifier. I thought that I would neither be able to read nor instantiate such modified attributes without using getters and setters.

public class Test {
    private int radius = 3;
    private int age;

    public static void main(String[] args) {
        Test a = new Test();
        System.out.println(a.radius);
        System.out.println(a.age);
    }
}

Upvotes: 0

Views: 1251

Answers (2)

Pankaj
Pankaj

Reputation: 54

Methods, variables, and constructors that are declared private can only be accessed within the declared class itself.

Private access modifier is the most restrictive access level. Variables that are declared private can be accessed outside the class, if public getter methods are present in the class.

Using the private modifier is the main way that an object encapsulates itself and hides data from the outside world.

Upvotes: 0

fesieg
fesieg

Reputation: 478

private only means these variables can't be directly accessed from outside the class. All methods inside the class can use the variable freely.

Upvotes: 1

Related Questions