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.
Solved!
Any tips on how to access private variables of a different instance of object but same class without using setter or getters as well?
Thanks
Edit: A sample code with what I am trying to achieve https://pastebin.com/P1GXhwQv
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?
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!
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.
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.
I do not know why I am so confused about this. I have been trying understand the point of a getter and setter. Can someone please explain to me the difference and what both are for?
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?
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.
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.
You can access those values, and manipulate them via Reflection. By this mechanism you can check fields and invoke methods.
Using java.lang.reflect.Member.setAccessible(true) will override any privacy at runtime (not that there is much – the JVM will happily access private fields or methods given their name, see this answer.
I don't see the point. The only thing's accessing the variables are things that you choose to access them as a the developer. So I don't really see what the purpose of updating variables with a method vs using the value directly
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).
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.
If we have a class with a lot of variables and each variable needs a getter and setter wouldn't that clutter up the code?