Java Reference
In-Depth Information
Let's discuss some examples of using the access level modifiers for class members, and their effects. Consider the
code for the AccessLevel class shown in Listing 6-14.
Listing 6-14. An AccessLevel Class with Class Members Having Different Access Levels
// AccessLevel.java
package com.jdojo.cls;
public class AccessLevel {
private int v1 = 100;
int v2 = 200;
protected int v3 = 300;
public int v4 = 400;
private void m1() {
System.out.println("Inside m1():");
System.out.println("v1 = " + v1 + ", v2 = " + v2 +
", v3 = " + v3 + ", v4 = " + v4);
}
void m2() {
System.out.println("Inside m2():");
System.out.println("v1 = " + v1 + ", v2 = " + v2 +
", v3 = " + v3 + ", v4 = " + v4);
}
protected void m3() {
System.out.println("Inside m3():");
System.out.println("v1 = " + v1 + ", v2 = " + v2 +
", v3 = " + v3 + ", v4 = " + v4);
}
public void m4() {
System.out.println("Inside m4():");
System.out.println("v1 = " + v1 + ", v2 = " + v2 +
", v3 = " + v3 + ", v4 = " + v4);
}
}
The class has four instance variables called v1 , v2 , v3 , and v4 and four instance methods called m1() , m2() , m3() ,
and m4() . Four different access level modifiers have been used for instance variables and instance methods. I have
chosen to use instance variables and methods in this example; the same access level rules apply to class variables and
class methods. The code for the AccessLevel class compiles without any errors. Note that no matter what the access
level for a class member is, it is always accessible inside the class in which it is declared. This can be verified by the
fact that you have accessed (read their values) all instance variables, which have different access levels, inside all
four methods.
Let's consider the AccessLevelTest1 class shown in Listing 6-15.
 
Search WWH ::




Custom Search