Java Reference
In-Depth Information
Access Specifi ers for Top-Level Classes
A top-level class has two options for an access modifi er: public or package-level access
(often called the default access). Keep an eye out for exam questions that declare a top-
level class as private or protected . For example, the following code will not compile:
//Generates a compiler error: “modifier private not allowed here”
private class HelloWorld {
public static void main(String [] args) {
System.out.println(args[1] + args[2]);
}
}
Multiple Classes in a Single File
Java allows multiple top-level classes to be defi ned in a single fi le, but in the real world
this is rarely done. We typically want our classes to be public, and only top-level classes
can be public. That being said, the exam might contain questions that defi ne multiple
classes in a single source fi le because it is convenient and many questions on the exam
involve more than one class.
Packages
The exam objectives state that you need to be able to “write code that uses the appropriate
package declarations and import statements,” and I can assure you there will be more than
one question on the exam testing your knowledge of the package keyword and its effect
on a Java class. This section discusses the details you need to know about Java packages.
A package is a grouping of classes and interfaces. It can also contain enumerations and
annotated types, but because these are special types of classes and interfaces, I will refer
to items in a package as simply classes and interfaces for brevity. This grouping of classes
and interfaces is typically based on their relationship and usage. For example, the java.io
package contains classes and interfaces related to input and output. The java.net package
contains the classes and interfaces related to networking. There are two key benefi ts of
using packages in Java:
Packages organize Java programs by grouping together related classes and interfaces.
Packages create a namespace for your classes and interfaces.
The Application Programming Interface (API) for the Java Platform, Standard Edition
(Java SE) contains hundreds of packages that you can use in any Java SE application. As
Search WWH ::




Custom Search