Java Reference
In-Depth Information
//int a = al.v1; /* A compile-time error */
//int b = al.v2; /* A compile-time error */
//int c = al.v3; /* A compile-time error */
int d = al.v4;
System.out.println("d = " + d);
//al.m1(); /* A compile-time error */
//al.m2(); /* A compile-time error */
//al.m3(); /* A compile-time error */
al.m4();
/* Modify the values of instance variables */
//al.v2 = 20; /* A compile-time error */
//al.v3 = 30; /* A compile-time error */
al.v4 = 40;
System.out.println("After modifying v4...");
//al.m2(); /* A compile-time error */
//al.m3(); /* A compile-time error */
al.m4();
}
}
d = 400
Inside m4():
v1 = 100, v2 = 200, v3 = 300, v4 = 400
After modifying v4...
Inside m4():
v1 = 100, v2 = 200, v3 = 300, v4 = 40
Note the AccessLevelTest2 class in the com.jdojo.cls.p1 package, which is different from the com.jdojo.cls
package in which the AccessLevel class exists. The code for the AccessLevelTest2 class is similar to the code for the
AccessLevelTest1 class, except for the fact that most of the statements have been commented. Note that you need to
use an import statement to import the AccessLevel class from the com.jdojo.cls package so you can use its simple
name inside the main() method. In the AccessLevelTest1 class, it was not necessary to import the AccessLevel
class because they are in the same package. The AccessLevelTest2 class can access only the public members of
the AccessLevel class because it is in a different package than the AccessLevel class. This is the reason that the
uncommented statements access only the public instance variable v4 and the public method m4() . Note that even if
only the v4 instance variable is accessible, you are able to print the values of v1 , v2 , and v3 as well, by accessing them
indirectly through the public method m4() .
Let's consider a trickier situation. See Listing 6-17.
Listing 6-17. A Class with Package-level Access Having a Public Instance Variable
// AccessLevel2.java
package com.jdojo.cls;
class AccessLevel2 {
public static int v1 = 600;
}
 
Search WWH ::




Custom Search