GeeCON Prague 2014*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Sample question Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Sample question" Watch "Sample question" New topic
Author

Sample question

Andy Wong
Greenhorn

Joined: May 28, 2001
Posts: 20
The following question is taken from http://www.jchq.net/mockexams/exam3.htm
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;
}
}
1) Compile time error, the variable court is defined as private
2) Compile time error, s is not initialized when the System.out method is called
3) Compilation and execution with no output
4) Compilation and run with an output of 99

The correct answer is 4. However, why it is not 1 since the variable is private, we cannot access it using s.court. That's why we have the getters and setters method, am I right?
Andy
Charlie Swanson
Ranch Hand

Joined: Jan 29, 2001
Posts: 213
<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;
}
}
</CODE>
1) Compile time error, the variable court is defined as private
The correct answer is 4. However, why it is not 1 since the variable is private, we cannot access it using s.court. That's why we have the getters and setters method, am I right?
Private is an acceptable member variable. A private member variable is only accessible to the class that created it. In this case, since it is only being referred to by the class we do have access to it.
If we wanted to refer to it in the class we could say s.court.
However, if it was another class referring to the private variable, it would not work.
The getters and setters can be used to access the private member variables, and they do limit what outside classes can do.
Hope this helps.
Bin Wang
Ranch Hand

Joined: May 01, 2001
Posts: 82
Remember you are using s.court within the main method of class Sandys. In the same class, methods can access private variables.
If s.court is used in the main method of another class, then compile error.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Sample question