Access Private Field of Another Object in Same Class

Access private field of another object in same class

I am also a bit curious with the answer.

The most satisfying answer that I find is from Artemix in another post here (I'm renaming the AClass with Person class):
Why have class-level access modifiers instead of object-level?

The private modifier enforces Encapsulation principle.

The idea is that 'outer world' should not make changes to Person internal processes because Person implementation may change over time (and you would have to change the whole outer world to fix the differences in implementation - which is nearly to impossible).

When instance of Person accesses internals of other Person instance - you can be sure that both instances always know the details of implementation of Person. If the logic of internal to Person processes is changed - all you have to do is change the code of Person.

EDIT:
Please vote Artemix' answer. I'm just copy-pasting it.

private member variable is accessed by another object of same class?

you are not accessing c.value outside of the c object.

What you are doing is accessing a private variable of a class in the same class. Because the c variable is of exactly the same type as the class, you can access private variable c.value in that class.

Imagine the following situation

public class HelloWorld 
{
public static void main(String[] args)
{
OtherClass myObject = new OtherClass(7);
OtherClass yourObject = new OtherClass(4);
yourObject.value = 23;
System.out.print(myObject.compareTo(yourObject));
}
}

public class OtherClass
{
private int value;
OtherClass(int value)
{
this.value = value;
}

public int compareTo(OtherClass c)
{
return this.value - c.value;
}
}

Your code would not compile because value is not accessible from any class other than OtherClass. However, if you try to access c.value you will certainly succeed in doing that.

You would understand better if you study encapsulation more, and a good source of information is the [official documentation](https://docs.oracle.com/javase/tutorial/java/concepts/object.html"Oracle Documentation")

Java: Accessing private fields directly from another instance of the same class

No, it's not. The reason that private variables and methods are not accessable from other classes is to allow you to change the internals of your class without having to change all the code that uses the class (that and to prevent the user of your class from e.g. setting a variable to a value that it's never supposed to have).

If you use private variables of other objects that doesn't hurt anything, because if you'd restructure your class's internals, you'd have to change the code inside the class anyway.

Why is it allowed to access a private field of another object?

Private fields protect a class, not an instance. The main purpose is to allow a class to be implemented independently of its API. Isolating instances between themselves, or protecting the instance's code from the static code of the same class would bring nothing.

A private variable can be accessed from another object of the same type?

Methods of a class can access its private attributes throughout all class instances, at least in C++.

Why can an instance of a class access private fields of another instance of its own type?

First you have to ask "why have private fields at all?"

Private fields are primarily for encapsulation: a consumer of a class shouldn't have to know the internals of that class' implementation, and in fact those internals should be actively hidden from the consumer. Otherwise, if a user relied on those internals, then the implementer would be forced to support them or break backwards compatibility. In other words, it protects both the user and designer of the class:

  • users are protected from implementation changes breaking their code
  • the designer is protected from having to keep implementation details features unchanged forever

But a class doesn't need to be protected from itself; it doesn't need to worry about the case where one bit of its code changes, but another bit (that uses the first bit) can't change. Backwards compatibility is not a concern, because the class is developed and deployed as a single, atomic chunk of code. In other words, neither of the above protections are needed.

Since there's no need to protect the fields, and since it's often necessary to see them (for instance, to compare if two objects are equal), they're visible within the class.

Assigning private field of object in another class using list of same object c#

There're several possible options.

  1. Make it public (not recommended, because it's bad)
  2. Create a public property for access
  3. Create a public method to set the value (basically the same as second option)
  4. Do it with reflection

I would prefer the second option, because I think it's the cleanes way. When you have no chance to change the modifier you will have to use the fourth option.

How to read the value of a private field from a different class in Java?

In order to access private fields, you need to get them from the class's declared fields and then make them accessible:

Field f = obj.getClass().getDeclaredField("stuffIWant"); //NoSuchFieldException
f.setAccessible(true);
Hashtable iWantThis = (Hashtable) f.get(obj); //IllegalAccessException

EDIT: as has been commented by aperkins, both accessing the field, setting it as accessible and retrieving the value can throw Exceptions, although the only checked exceptions you need to be mindful of are commented above.

The NoSuchFieldException would be thrown if you asked for a field by a name which did not correspond to a declared field.

obj.getClass().getDeclaredField("misspelled"); //will throw NoSuchFieldException

The IllegalAccessException would be thrown if the field was not accessible (for example, if it is private and has not been made accessible via missing out the f.setAccessible(true) line.

The RuntimeExceptions which may be thrown are either SecurityExceptions (if the JVM's SecurityManager will not allow you to change a field's accessibility), or IllegalArgumentExceptions, if you try and access the field on an object not of the field's class's type:

f.get("BOB"); //will throw IllegalArgumentException, as String is of the wrong type

Access of private field of another object in copy constructors - Really a problem?

I see no problem with the code. In fact, I share your concerns and would prefer to not use getters.

What exactly is the warning you get? Maybe it is related to something you are not showing us?

Update: Seems Netbeans is really complaining about just that. That is a rather controversial warning to ship with an IDE, I would think.



Related Topics



Leave a reply



Submit