What does it mean to access a class? When we say a class has access to another class, it means it has the ability to do one of three things:
· create an instance of another class
· extend a class
· access certain methods and variables within the class
In effect, to have access means the class is visible. Within each class, access control determines individually which methods and variables may be accessed. Access control is important because it controls visibility of a class, a method, or a variable. This means that you can control the external appearance or interface for a class, a method, or a variable. Controlling the visible application programming interface (API) of a class is called encapsulation, which is an important feature of object-oriented design (Chapter 7 deals with this).
Default access
A class with default access needs no modifier preceding it in the declaration. Default access allows other classes within the same package to have visibility to this class, but a class member or constructor is not accessible in any other package. Examine the following source file:
import certification.SuperClass;
class SubClass extends SuperClass{
static public void main(String [] args) {
System.out.println(”SubClass.”);
}
}
Examine the second source file:
package certification;
class SuperClass{
static public void main(String [] args) {
System.out.println(”SuperClass!”);
}
}
As you can see, we have a superclass that resides in a different package from the subclass. The subclass has no package declaration; therefore, it is placed into an unnamed default package. The import statement at the top of the SubClass file is attempting to import the SuperClass class. The superclass belongs to the certification package, and it compiles fine. Watch what happens when we try to compile the SubClass file:
c:\Java Projects\Package>javac Package.java
Package.java:1: Can’t access class certification.SuperClass. Class or
interface must be public, in same package, or an accessible member
class.
import certification.SuperClass;
..
This example does not work because the superclass is in a different package from the subclass. There are two ways to make this work. We could leave both classes as default access and add SubClass to the package certification. The other way is to declare SuperClass as public, as the next section describes.
Public access
The public keyword placed in front of a class allows all classes from all packages to have access to a class. In other words, all classes in the Java Universe have access to a public class. It is still necessary to import the class with the import statement if it belongs to another package, but otherwise it is completely usable by all other classes.

