The only way to access to private fields is with the Reflection API as next:

Field field1 = A.class.getDeclaredField("field1");
// Make it accessible as it is a private field otherwise you won't be able to get the value
field1.setAccessible(true);
MyClass obj = (MyClass) field1.get(a);

However using Reflection API should be your last resort as it is more a hack in this case than a real solution.

Answer from Nicolas Filotto on Stack Overflow
🌐
Reddit
reddit.com › r/learnprogramming › java class: why do you make fields private?
r/learnprogramming on Reddit: Java class: Why do you make fields private?
February 19, 2024 -

If I were to make public getters and setters to access those private fields of a class, why not just make those fields public from the beginning? If I make them public from the beginning, I don't have to have getters and setters and make the code simple, right?

Top answer
1 of 32
102
Some languages "fix" this problem so you don't have to write getters/setters. One reason is to control the range of values. Let's say you had a salary field. Salaries are supposed to be positive, right? You declare it as a double. Now it can be negative. Also, once it becomes public, anyone can change it. Now, getters/setters allow the same thing, but you can choose to only allow getters and not allow setters. Or you could hide some variables altogether. For example, there's a hashtable (HashMap). Hash tables are supposed to increase in size once the number of objects in it increase. But, as a person using a hash table, I don't care about the data structure that holds my hash table and how it chooses a hash function and how it resizes the hash table. There are classes where it's not just Java classes that are plain getter/setters. They do a lot internally, and making the internals public might affect the correct behavior of that class/object.
2 of 32
26
Two reasons - backwards compatibility and cultic devotion. For the first reason - if a class is part of the public interface of a library, going froma public attribute to a getter/setter is a breaking change. So if you do need a getter/setter latter (for caching, validation, or any other reason), that is now a breaking API change. Breaking changes are expensive for consumers. In the past such changes were much more expensive because automated refactoring tools were much more limited. Now for the cult bit. Java culture has historically been dominated by people who are... A bit obsessed with a particular idiom of object oriented programming. In classic OOP, there's no such thing as a public property. The only way to manipulate a class is to send it a message. In Java, sending messages is calling methods. So to adhere strictly to the OOP model, no public properties are allowed. The problem with this is there isn't really a good reason for this rule in practical programming. Any more than there is a good reason to completely forbid break statements in structured programming. But programmers like their little religions.
🌐
Reddit
reddit.com › r/learnjava › using getters or directly accessing private variables inside an object of the same class
r/learnjava on Reddit: Using getters or directly accessing private variables inside an object of the same class
February 10, 2022 -

Hello! This is my first time posting here so if there are any problems with the post, contact me to fix them.

My question came from part05-Part05_11.ComparingApartments of MOOC.fi.
The exercise is about accessing variables from other objects of the same class.

I first solved the problem using getters. Then I saw the model solution and they just access the variables directly, so I changed the code to utilize direct access.

And here comes my question - Which way is better and why (unless it's a personal preference / project guideline)?

Thanks!

Top answer
1 of 5
2
i'm currently at part 06_13 What I understood is that getters exist because when class variables are private you can't access them from a different class or the main program so you need to use a getter method if you want to access them from outside the class. I wouldn't say one is better than the other. I just use a pragmatic approach, if i'm not going to need access from outside then i'm not creating a getter.
2 of 5
2
For one, using getters / setters inside the class is a little bit more code to no benefit. The better reason to use direct access is something else, though: You define getters and setters with outside access in mind. Quite often you'll have fields that aren't supposed to be changed outside your class, maybe not even be visible outside your class. They won't have getters / setters so direct access is the only way to use them. Take the following example. class DeckOfCards { private List cards; // Constructor, no getters, no setters private void shuffle() { Collections.shuffle(cards); } private Card draw() { return cards.remove(0); } } A deck of cards may hold a list of cards on the inside but you probably don't want to expose it to the outside. The next draw wouldn't be much of a surprise if anyone could just access cards and look at all cards and their order in the deck. Or change them, even, adding and removing cards at will. If you exposed the list of cards to the outside all of that would be possible. So you don't. Instead you expose just those methods you want to be used, like shuffling or drawing. This requires direct access, you don't have getters / setters and you don't want them either.
🌐
Reddit
reddit.com › r/learnjavascript › why are inherited private class fields not accessible on the subclass, after instantiation? +are there any workarounds?
r/learnjavascript on Reddit: Why are inherited private class fields not accessible on the subclass, after instantiation? +are there any workarounds?
December 6, 2025 -

tldr: i found a method to pass values to private properties declared "further up the chain".. in a subclass definition. i was pleased with this, very pleased, but then i realized that afterwards, even while using getters/setters the private properties are inaccessible on the object, despite the JavaScript debug console showing them on them.

i know there is high strangeness around private properties. But it would mean the world to me, if i could just access them.. somehow.

🌐
Coderanch
coderanch.com › t › 785108 › java › setter-getter-works-accessing-private
If setter and getter works well for accessing private fields, then why not private methods? (Beginning Java forum at Coderanch)
October 13, 2024 - Likewise you can use a "setter" method to assign a particular value in an object; often that means to set the value of a (private) field in the object. Now, there are other things that "getter" and "setter" methods might do. But typically they are public methods so that instances of other classes ...
🌐
Reddit
reddit.com › r/learnprogramming › if you make a getter and setter methods for a private variable, doesn't that defeat the purpose of "privatizing" a variable?
r/learnprogramming on Reddit: If you make a getter and setter methods for a private variable, doesn't that defeat the purpose of "privatizing" a variable?
November 27, 2023 -

I'm still qute new in encapsulation ideas. In python, you could access non private variables of a class using the dot operator. You could do everything that a getter and setter method would do, by just using the dot operator. But if you privatize it, by adding a dunder in front of the variable, you can't do this anymore and need to rely on getter and setter methods. So if you implement both methods, why don't you just don't privatize the variable?

I can see the point if we just implemented a getter or setter method independently, but not implementing them BOTH. cause if we implement them both, just don't privatize the variable and reduce a few lines of code.

Find elsewhere
🌐
Reddit
reddit.com › r/java › why should fields be kept private?
r/java on Reddit: Why should fields be kept private?
October 15, 2014 -

Hey r/java!

I'm currently taking Comp Sci in HS, and I have a strong background of JavaScript, Python, and Ruby.

Recently the teacher/textbook told us that fields are best kept private, and that a getFieldName method is the way to access the value of that field.

This doesn't make any sense to me. When you've got a method called getName() which just returns name, why not make name a public field?

Top answer
1 of 5
42

There are a few reasons, one of which is simply that many tools will expect your classes to conform to the Java Beans specification and attempt to manipulate your objects using the getter and setter functions.

In addition, by making the fields private you ensure that all modifications to them will have to happen under your control. Your setter might perform validation or edit checks on the values being passed, whereas raw access to the field won't have that level of safety. You can't mark a field 'private write/public read' so that makes using a getter a necessity.

Also, you may find that a few weeks down the road you've delegated responsibility for the values in those fields to some other object, so you change your getter code from this:

String getName() {
    return name;
}

to

String getName() {
    return getNameHelper().getName();
}

and remove the name field altogether. If you are referring to it directly you will be a lot more reluctant to refactor in this way since you may have to change a couple of dozen other source modules.

2 of 5
19

So here's my basic example:

public class Item {
    private String name;
    public String getName() {
        return name;
    }
    public void setName(String name) {            
        Log.i("ITEM", "Name changed from outside of object.");
        this.name = name;
    }
}

In this example, a log event is fired when the name is changed. Since this is the only way to change the name from outside the class, it will always fire.

Now, this is a trivial example, but it gets to the point where you can see that there's some sort of process that happens every time the field is set. You could similarly fire something every time it's accessed, for access control methods.

The reason we design like this all the time, is because you never know when you're going to need to add one of those extra little processes. If you start out with a public field, people writing against your code are going to read and write the field directly, so if you change your mind later, you either break their code, or leave a hole in your program.

Does that make sense?

u/RhoOfFeh makes a really good point about Beans, too, but that's a little bit further down the road from where you are now.

🌐
Baeldung
baeldung.com › home › java › core java › reading the value of ‘private’ fields from a different class in java
Reading the Value of 'private' Fields from a Different Class in Java | Baeldung
November 13, 2025 - Let’s define a sample class Person ... // getters and setters } To make any private field accessible, we have to call the Field#setAccessible method: Person person = new Person(); Field nameField = person.getClass().getDeclar...
🌐
Stack Overflow
stackoverflow.com › questions › 65250376 › flutter-classes-objects-are-accessing-private-fields-without-getters
dart - Flutter Classes Objects are accessing private fields without getters - Stack Overflow
So lets come to your question, your main method is able to access a field started with '_' because there are in the same package. Create a new file and move your class to that file, and you will not be able to access the private member.
🌐
Medium
medium.com › web-factory-llc › private-fields-private-methods-private-accessors-javascript-finally-with-privacy-classes-4a476d9cd679
Private fields, private methods, private accessors. Javascript finally with privacy classes
July 23, 2020 - Defining private fields in class (and using them in object — instance for that class) means accessing that field will be allowed only to the current object (inside that same class). Setting value for that variable or getting it needs to be done by setter and getter.
🌐
Coderanch
coderanch.com › t › 469536 › java › Accessing-private-variables-class
Accessing private variables directly from outside the class (Beginning Java forum at Coderanch)
November 4, 2009 - Thanks a lot for your replies guys. So it means that the private variables just cannot be accessed from other classes. If the instance is created in the same class itself the private variable of that instance can be accessed directly.
Top answer
1 of 2
3

There are two arguments why you'd rather not expose public fields:

  • This limits future evolution of your design, assuming you need to offer a stable API.
  • This tends to lead to higher coupling between components, in particular to more complex data flows between components. And complexity leads to bugs.

Let's first discuss API stability.

There are two different kinds of codebases: one kind contains applications and in-house code. Everything is under your control and can be refactored freely. The other kind is a library with external consumers. Now you need to think about API stability, because you can't just change stuff. Code that worked with the old API should continue to work with the new API.

In applications, API stability doesn't matter because you can always refactor anything, and all dependent code along with it. Much of the OOP architecture advice you might read doesn't apply to applications.

Libraries are more tricky. Your first public design should be close to the ideal design, or at least allow opportunity for future evolution in a backwards-compatible manner. When we have a public member variable, we commit to there always being this variable. The variable will also accept any value when set, except as restricted by its type.

Properties and accessor methods are much more flexible. For example, we can remove the variable and re-compute it on the fly. Or we can add validation code. Or we can trigger events when a variable is updated. Since properties and accessor methods allow us to supply arbitrary code, this is much more flexible. In C#, a class that is part of a public API should almost always use auto-properties in place of public fields due to this future-compatibility aspect.

Another nice aspect in C# is that properties can be part of interfaces. This may also help with creating loosely coupled interfaces between components. This works because properties are just a different syntax for special methods.

The other aspect I mentioned is that using methods can lead to simpler data flows and less coupling between components.

One reason is that methods/properties let us separate the public API from our private implementation. E.g. we might not want to have other components assign to a field directly. In that case, a private set property might be very useful.

But allowing unrestricted getting/setting might not be a particularly good API for our object. An object should not be a bunch of named fields (whether as plain fields, properties, or getters/setters), but should provide some capabilities to its users. We should be able to tell an object to just do a thing, not ask the object for all data necessary so we can do the thing ourselves (see Tell-Don't-Ask by Martin Fowler).

2 of 2
1

Also: "sometimes it makes perfect sense to use getters and setters, even for purely-private fields." And that of course depends on: "what is this field?"

For instance: "this value is actually computed, and therefore I could fill my code with calls to some private function." Well, a "getter" and maybe a "setter" is actually the same thing ... but it might make your code read a whole lot cleaner. They let the writer of source-code ignore the fact that there is a function-call involved, while also concentrating the implementation into one place so that, when necessary, you can easily change it in that one place. "Just do whatever your source-code writers prefer."

P.S.: A "getter/setter" is also a great place to hide assert() calls.