/* This program demonstrates the difference between
public and private.
*/
class Test {
int a; // default access
public int b; // public access
private int c; // private access
// methods to access c
void setc(int i) { // set c's value
c = i;
}
int getc() { // get c's value
return c;
}
}
class AccessTest {
public static void main(String args[]) {
Test ob = new Test();
// These are OK, a and b may be accessed directly
ob.a = 10;
ob.b = 20;
// This is not OK and will cause an error
//
ob.c = 100; // Error!
// You must access c through its methods
ob.setc(100); // OK
System.out.println("a, b, and c: " + ob.a + " " +
ob.b + " " + ob.getc());
}
}
As you can see, inside the Test class, a uses default access, which for this example is the
same as specifying public. b is explicitly specified as public. Member c is given private
access. This means that it cannot be accessed by code outside of its class. So, inside the
AccessTest class, c cannot be used directly. It must be accessed through its public methods:
setc( ) and getc( ). If you were to remove the comment symbol from the beginning of the
following line,
//
ob.c = 100; // Error!
then you would not be able to compile this program because of the access violation.
To see how access control can be applied to a more practical example, consider the
following improved version of the Stack class shown at the end of Chapter 6.
// This class defines an integer stack that can hold 10 values.
class Stack {
/* Now, both stck and tos are private.  This means
Search WWH :
Custom Search
Previous Page
Java SE 6 Topic Index
Next Page
Java SE 6 Bookmarks
Home