Java Reference
In-Depth Information
The
AccessLevel
and
AccessLevelTest1
classes are in the same package.
AccessLevelTest1
can access all
class members of the
AccessLevel
class, except the ones declared
private
. You cannot access the instance
variable
v1
and the instance method
m1()
of the
AccessLevel
class from the
AccessLevelTest1
class because their
access level is
private
. If you uncomment the two statements in the
AccessLevelTest1
class, which attempts to
access the
private
instance variable
v1
and the
private
instance method
m1()
of the
AccessLevel
class, you would
receive the following compiler error:
"AccessLevelTest1.java": v1 has private access in com.jdojo.cls.AccessLevel at line 7, column 16
"AccessLevelTest1.java": m1() has private access in com.jdojo.cls.AccessLevel at line 12, column 8
The
AccessLevelTest1
class reads the values of the instance variables of the
AccessLevel
class, as well as
modifies them. You must note one thing: even though you cannot access the
private
instance variable
v1
and the
private
method
m1()
of the
AccessLevel
class from the
AccessLevelTest1
class, you are able to print the value of the
private
instance variable
v1
as shown in the output.
An access level modifier for a class member specifies who can access them directly. If a class member is not
accessible directly, it might be accessible indirectly. In this example, the instance variable
v1
and the instance method
m1()
are not directly accessible from outside the
AccessLevel
class; however, they may be indirectly accessible from
outside. Indirect access to an inaccessible class member is usually given by providing another method, which is
accessible from outside.
Suppose you want the outside world to read and modify the value of the otherwise inaccessible
private
instance
variable
v1
. You need to add two
public
methods,
getV1()
and
setV1()
, to the
AccessLevel
class; these two methods
will read and modify the value of the
v1
instance variable. Your modified
AccessLevel
class would look as follows:
public class AccessLevel {
private int v1;
/* Other code goes here */
public int getV1() {
return this.v1;
}
public void setV1(int v1) {
this.v1 = v1;
}
}
Now, even if the private instance variable
v1
is not directly accessible from outside, it is made indirectly
accessible through the
public
methods
getV1()
and
setV1()
. Let's consider another test class as shown in
Listing 6-16.
Listing 6-16.
A Test Class Located in a Different Package from the AccessLevel Class
// AccessLevelTest2.java
package com.jdojo.cls.p1;
import com.jdojo.cls.AccessLevel;
public class AccessLevelTest2 {
public static void main(String[] args) {
AccessLevel al = new AccessLevel();