Two Laptop Bag
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Help for the visibility of private access modifier Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


Win a copy of The Mikado Method this week in the Agile and other Processes forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Reply Bookmark "Help for the visibility of private access modifier" Watch "Help for the visibility of private access modifier" New topic
Author

Help for the visibility of private access modifier

Jack Lee
Ranch Hand

Joined: Jun 06, 2006
Posts: 38
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
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.
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 16695
    
  19

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.

Henry


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
 
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to run our stuff on 16 servers instead of 3.
 
subject: Help for the visibility of private access modifier
 
Similar Threads
Marcus Green #3 Q45
get method
Sample question
private member doubt
Marcus Green exam question