• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Sample question

 
Andy Wong
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 213
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
<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
Posts: 82
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic