An instance of a class, in Java, can access private fields of a different instance of its own type, such as in the following listing:
public class Foo { private int secret; public void bar(final Foo foo) { foo.secret = 100; } }
What would be the argument for such semantics (when designing a language)?
Private: The class members declared as private can be accessed only by the functions inside the class. They are not allowed to be accessed directly by any object or function outside the class. Only the member functions or the friend functions are allowed to access the private data members of a class.
Any method within your class can access the private data of any instance of that class; there's not a way to keep data private to within an instance unless you forbid methods that explicitly access private data members of other instances.
By using Public Method We can access a private variable in a different class by putting that variable with in a Public method and calling that method from another class by creating object of that class.
This is perfectly legal. Objects of the same type have access to one another's private variables. This is because access restrictions apply at the class or type level (all instances of a class) rather than at the object level (this particular instance of a class).
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:
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.
The private
field is meant to tell other programmers not to mess with it.
Presumably, everyone working in a single class knows what all the variables do. The private
field doesn't hide your own code from you, just from outside.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With