Java Reference
In-Depth Information
Note that there is no access level modifier used for the
AccessLevel2
class, which gives it a package-level access
by default. That is, the
AccessLevel2
class is accessible only within the
com.jdojo.cls
package. The
AccessLeve2
class is simple. It declares only one member, which is the
public static
variable
v1
.
Let's consider the class
AccessLevelTest3
shown in Listing 6-18, which is in a different package than the class
AccessLevel2
.
Listing 6-18.
A Test Class That Attempts to Access a Public Member of a Class with a Package-level Access
// AccessLevelTest3.java
package com.jdojo.cls.p1;
import com.jdojo.cls.AccessLevel2; // A compile-time error
public class AccessLevelTest3 {
public static void main(String[] args) {
int a = AccessLevel2.v1; // A compile-time error
}
}
The
AccesssLeveTest3
class attempts to access the
public static
variable
v1
of the
AccessLevel2
class, which
generates a compiler error. Did I not say that a class member with
public
access level is accessible from anywhere?
Yes. I did say that. Here is the catch. Suppose you have some money in your pocket and you declare that your money
is public. Therefore, anyone can have your money. However, you hide yourself so that no one can have access
to you. How can anyone access your money unless you become accessible to him first? This is the case with the
AccessLevel2
class and its
public static
variable
v1
. Compare the
AccessLevel2
class with yourself, and its
public
static
variable
v1
with your money. The
AccessLevel2
class has package-level access. Therefore, only the code
within its package (
com.jdojo.cls
) can access its name. Its
static
variable
v1
has the access level of
public
, which
means any code can access it from any package. The
static
variable
v1
belongs to the
AccessLevel2
class. Unless the
AccessLevel2
class itself is accessible, its
static
variable
v1
cannot be accessed, even though it has been declared
public
. The
import
statement in Listing 6-18 will also generate a compiler error for the reason that the
AccessLevel2
class is not accessible outside its package
com.jdojo.cls
.
■
You must consider the access level of both the class and its member to determine whether a class member is
accessible. the access level of a class member may make it accessible to a part of a program. however, that part of a
program can access the class member only if the class itself, to which the member belongs, is also accessible.
Tip
Access Level—A Case Study
A class member can have one of the four access levels:
private
,
protected
,
public
, or package-level. Which access
level should be used with a class member? The answer depends on the member type and its purpose. Let's discuss an
example of a bank account. Suppose you create a class
Account
to represent a bank account.
// Account.java
package com.jdojo.cls;
public class Account {
public double balance;
}