Help for the visibility of private access modifier
Jack Lee
Ranch Hand
Joined: Jun 06, 2006
Posts: 38
posted
0
The following code:
public class Sandys{ private int court; public static void main(String argv[]){ Sandys s = new Sandys(99); System.out.println(s.court); }
Sandys(int ballcount){ court=ballcount; } }
I compiled and run it. The output is 99
My question is: Why can the Sandys' main() method access s.court?
The member variable "court" is defined as private, the only way to get its value is to use accessible instance's member method.
In the above code, the main method is static and belong to the Sandy Class object. Is the Sandys.class object able to access Sandys' instance object s' private member variables?
SCJP 5.0<br />SCWCD 1.4
wise owen
Ranch Hand
Joined: Feb 02, 2006
Posts: 2023
posted
0
Static methods may not access the instance variables of their class (or any other class for that matter), other that via some object reference, e.g. s.court. Static methods may even access private instance variables in their class via some object reference.
Private instance variables are private to the class -- meaning it can be accessed by static methods of the class. And it also means that it can be accessed by any instance of that same class.