I was under the impression that private non-static variables could only be accessed by methods called on the object that the variables reside in, but this is not the case. Could someone please explain the reasoning behind why the following compiles and runs?
public class Sandbox {
private String _privateString = "unmodified";
public static void setPrivateString(String str, Sandbox s) {
s._privateString = str;
}
public String toString()
{
return _privateString;
}
public static void main(String[] args) {
Sandbox s = new Sandbox();
setPrivateString("modified", s);
System.out.println(s);
}
}
Output:
modified
EDIT: The same is true in C#.
We cannot directly access the instance variables within a static method because a static method can only access static variables or static methods. An instance variable, as the name suggests is tied to an instance of a class.
A static member function has the same access rights as a non static member function. So yes, it can access any public, protected, and private variable in the class. However you need to pass an instance of the class to the function for the function to be able to access the member.
Static methods can access the static variables and static methods directly. Static methods can't access instance methods and instance variables directly. They must use reference to object. And static method can't use this keyword as there is no instance for 'this' to refer to.
No you cannot, by any means access the private variables in java. You can provide public getter and setter methods to access or change the value of the private member variables.
Private member variables of class A can be accessed (i.e. read/written to) by any method of class A (static or non-static), so in your example, since the method changing the string is a method of the same class the member belongs to, it is granted access to the variable.
The reason is because a class is considered a self-contained body of logic (i.e. a specific implementation), so it makes sense that privacy is contained within a class; there is no reason to exclude static methods from that access right, since they are also part of the specific implementation the class provides.
You seem to be confusing visibility
with scope
. The instance variables are in the scope of an instance, so they cannot be accessed in a static method directly, but only with an instance reference qualifier: s._privateString
in your case.
However, this does not mean that instance variables are not visible for a static method inside the same class, as private
means visible inside the class (for any member with any scope).
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