Programming and Problem Solving with Java

(やまだぃちぅ) #1

(^52) | Java Syntax and Semantics, Classes, and Objects
When we first showed the syntax template for a Java application, we mentioned that the
application can optionally include an import declaration. Import declarations can start any
class declaration. Here is the syntax diagram for such a declaration:
As the template shows, an import declaration begins with the keyword import, the name
of a package, and a dot (period). Following the period, we can either write the name of a
class in the package or type an asterisk (*). The declaration ends with a semicolon. If we
want to use exactly one class in a particular package, then we can simply give its name
(Class-name) in the import declaration. More often, however, we want to use multiple classes
in a package, and the asterisk is a shorthand notation to the compiler that says, “Import
whatever classes from this package that this class uses.”
Why would we ever want to use the first form, when the asterisk has the same effect and
is easier to type? The first form documents the specific class that we intend to use, and it
causes the compiler to warn us if we mistakenly attempt to use another class from the pack-
age. In this book, we typically use the asterisk instead of the Class-Name, but we
document the class(es) we are importing by including a comment.
The next line, the class heading, begins with zero or more class modifiers,
which are Java reserved words. The syntax diagram includes two of Java’s modi-
fiers that are relevant here: publicand private. They are called access modifiersbe-
cause they specify whether elements outside of the class can use the class. What’s
outside of the class? Any of the packages that we list in importdeclarations. Also,
every application class actually resides within a package called javathat is part of
the JVM. Thus, if we declare an identifier to be public, we allow the JVM and all im-
ported packages to make use of it. Because we want the JVM to be able to execute our ap-
plication class, we specify that its name be public.
The heading is followed by the body of the class: an open brace, a series of class decla-
rations, and a closing brace. The braces indicate where the body begins and ends, and the class
declarations contain all of the statements that tell the computer what to do. Here’s an ex-
ample of a Java class:
private classExample
{
charsomeLetter = ‘A’;
System.out.println(“someLetter is “+ someLetter);
}
Import-Declaration
import Package-name. ;
Class-Name



  • Access modifiers Reserved
    words in Java that specify where
    a class, method, or field may be
    accessed; two examples are
    publicand private

Free download pdf