You can access those values, and manipulate them via Reflection. By this mechanism you can check fields and invoke methods.

Answer from T.G on Stack Overflow
Discussions

java - Accessing fields of dependency without getters or reflection - Stack Overflow
Second of all, private means private, which means a private field can only be accessed within it's class, which means you'd have to create a method of more open restrictions in order to access it from outside, which means a Getter... --- Well, you could do it with reflection, by setting to accessible temporarily...But that'd be very wrong if your objective is "to not bloat the class"... ... @AndrewL. I know its invalid java... More on stackoverflow.com
🌐 stackoverflow.com
Java class: Why do you make fields private?
On July 1st, a change to Reddit's API pricing will come into effect. Several developers of commercial third-party apps have announced that this change will compel them to shut down their apps. At least one accessibility-focused non-commercial third party app will continue to be available free of charge. If you want to express your strong disagreement with the API pricing change or with Reddit's response to the backlash, you may want to consider the following options: Limiting your involvement with Reddit, or Temporarily refraining from using Reddit Cancelling your subscription of Reddit Premium as a way to voice your protest. I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns. More on reddit.com
🌐 r/learnprogramming
75
83
February 19, 2024
java - Why is it possible to access a field without a getter? - Stack Overflow
You're just using field access. Having a getSet() method would make no difference, as the Java compiler won't use an accessor method automatically for you. I suspect what you're missing is that private access isn't determined by the object whose member you're trying to access - the code in ... More on stackoverflow.com
🌐 stackoverflow.com
java - Access private property without get/set - Stack Overflow
At most you can switch the private with protected so whatever inherit it can access it directly. But yeah, you really can't. This property is associated to the method. It has to sport the parentheses () in Java. There's no way "yet" to do it like this in Java, it'd have to be some kind of pointer to a method. ... Having a getter and setter already breaks encapsulation in spirit, so don't hesitate to use public fields... More on stackoverflow.com
🌐 stackoverflow.com
April 25, 2017
🌐
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 - However, if we wish to access them, we can do so by using the Reflection API. Let’s define a sample class Person with some private fields: public class Person { private String name = "John"; private byte age = 30; private short uidNumber = ...
🌐
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.
Find elsewhere
Top answer
1 of 2
9

Referring to the official JPA specification (final version, JPA 2.1) in Section 2.2 (page 24) we find:

The persistent state of an entity is accessed by the persistence provider runtime either via JavaBeans style property accessors (“property access”) or via instance variables (“field access”). Whether persistent properties or persistent fields or a combination of the two is used for the provider’s access to a given class or entity hierarchy is determined as described in Section 2.3, “Access Type”.

In Section 2.3.1 (page 27) this definition is made more concrete - with respect to your question:

By default, a single access type (field or property access) applies to an entity hierarchy. The default access type of an entity hierarchy is determined by the placement of mapping annotations on the attributes of the entity classes and mapped superclasses of the entity hierarchy that do not explicitly specify an access type. [...]

• When field-based access is used, the object/relational mapping annotations for the entity class annotate the instance variables, and the persistence provider runtime accesses instance variables directly. All non-transient instance variables that are not annotated with the Transient annotation are persistent.

• When property-based access is used, the object/relational mapping annotations for the entity class annotate the getter property accessors, and the persistence provider runtime accesses persistent state via the property accessor methods. All properties not annotated with the Transient annotation are persistent.

The term directly refers to an access strategy which allows the manipulation of an object's field (value) without the need to use getter/setter methods. In Java and for most OR-mappers (at least the ones I know of) this is achieved via Introspection - using the Java Reflection API. This way, classes' fields can be inspected for and manipulated to hold/represent data values from the (relational) database entries (i.e., their respective columns).

For instance, the provider Hibernate gives the following explanation in their User Guide:

2.5.9. Access strategies

As a JPA provider, Hibernate can introspect both the entity attributes (instance fields) or the accessors (instance properties). By default, the placement of the @Id annotation gives the default access strategy.

Important note:

Be careful when experimenting with different access strategies! The following requirement must hold (JPA specification, p. 28):

All such classes in the entity hierarchy whose access type is defaulted in this way must be consistent in their placement of annotations on either fields or properties, such that a single, consistent default access type applies within the hierarchy.

Hope it helps.

2 of 2
2

The provider can use reflection to access a private field on a class instance.

🌐
Stack Overflow
stackoverflow.com › questions › 53056343 › accessing-the-fields-of-a-class-which-getters-are-private
java - Accessing the fields of a class which getters are private - Stack Overflow
My solution in situations like this is to add methods to return a copy of the private data so the privacy of the data is respected. In your case (with nearly all primitives) this is as simple as returning the value (Strings are immutable in Java). Best of luck. Daniel B. Chapman – Daniel B. Chapman · 2018-10-30 02:06:34 +00:00 Commented Oct 30, 2018 at 2:06 · I don't understand how returning an array of values is better than having public getters.
🌐
Programiz
programiz.com › java-programming › examples › access-private-members
Java Program to Access private members of a class
Become a certified Java programmer. Try Programiz PRO! ... class Test { // private variables private int age; private String name; // initialize age public void setAge(int age) { this.age = age; } // initialize name public void setName(String name) { this.name = name; } // access age public int getAge() { return this.age; } // access name public String getName() { return this.name; } } class Main { public static void main(String[] args) { // create an object of Test Test test = new Test(); // set value of private variables test.setAge(24); test.setName("Programiz"); // get value of private variables System.out.println("Age: " + test.getAge()); System.out.println("Name: " + test.getName()); } }
🌐
GeeksforGeeks
geeksforgeeks.org › java › how-to-access-private-field-and-method-using-reflection-in-java
How to Access Private Field and Method Using Reflection in Java? - GeeksforGeeks
February 5, 2021 - If we want to access Private Field and method using Reflection we just need to call setAccessible(true) on the field or method object which you want to access. Class.getDeclaredField(String fieldName) or Class.getDeclaredFields() can be used ...
🌐
Vultr Docs
docs.vultr.com › java › examples › access-private-members-of-a-class
Java Program to Access private members of a class | Vultr Docs
December 11, 2024 - In this code, you use reflection to access the private name field of the Person class. After obtaining the field, you call setAccessible(true) to override the access check, which lets you read the private field.
Top answer
1 of 5
41

Four disadvantages that I can think of:

  1. If you want to have a read-only and mutable form of the same entity, a common pattern is to have an immutable class Entity that exposes only accessors with protected member variables, then create a MutableEntity which extends it and adds setters. Your version prevents it.
  2. The use of getters and setters adheres to the JavaBeans convention. If you want to use your class as a bean in property-based technologies, like JSTL or EL, you need to expose public getters.
  3. If you ever want to change the implementation to derive the values or look them up in the database, you'd have to refactor client code. An accessor/mutator approach allows you to only change the implementation.
  4. Least astonishment - when I see public instance variables, I immediately look for who may be mutating it and worry that I am opening pandora's box because encapsulation is lost. http://en.wikipedia.org/wiki/Principle_of_least_astonishment

That said, your version is definitely more concise. If this were a specialized class that is only used within a specific package (maybe package scope is a good idea here), then I may consider this for one-offs. But I would not expose major API's like this.

2 of 5
37

Get rid of the getters/setters too, and you're fine!

This is a highly controversial topic amongst Java programmers.

Anyways, there's two situtation where i use public variables instead (!) of getters/setters:

  1. public final To me this signals "I'm immutable" much better than just a getter. Most IDEs will indicate the final modifier with a 'F' during auto-completion. Unlike with getters/setters, where you have to search for the absence of a setXXX.
  2. public non-final I love this for data classes. I just expose all the fields publicly. No getters, setters, constructors. No nothing. Less than a pojo. To me this immediately signals "look, i'm dumb. i hold data, that's all. it's YOUR job to put the right data inside of me". Gson/JAXB/etc. handle these classes just fine. They're a bliss to write. There's no doubt about their purpose or capabilities. And most importantly: You know there are no side effects when you change a variable. IMHO this results in very concise data models with few ambiguities, whereas getters and setters have this huge problem where sometimes magic happens inside of them.