(^46) | Java Syntax and Semantics, Classes, and Objects
Now let’s look at the syntax template for a Java application:
A Java application may optionally begin with a series of import declarations. As we noted
in Chapter 1, an object-oriented language such as Java provides a very large library of ready-
made objects that are available for us to use in our programs. Java’s library con-
tains so many, in fact, that they must be organized into smaller groups called
packages. Import declarations are statements that tell the Java compiler which li-
brary packages our program uses. We will look at how to write import declarations
shortly, but first let’s continue our examination of this syntax template.
The next line may optionally begin with a series of class modifiers, which are
then followed by the word class, and an identifier. This line is called the headingof
the class. An application in Java is a collection of elements that are grouped together
into a class. The heading gives the class a name (the identifier) and may optionally
specify some general properties of the class (the class modifiers). You’ve already
seen what an identifier is, and we define class modifiers later in this chapter.
The heading is followed by an open brace, a series of class declarations, and
a closing brace. These three elements make up the bodyof the class. The braces in-
dicate where the body begins and ends, and the class declarations contain all of
the statements that tell the computer what to do. The simplest Java program we can write
would look like this:
classDoNothing
{
}
As its name implies, this program does absolutely nothing. It is simply an empty shell of an
application. Our job as programmers is to add useful instructions to this shell.
When you finish this chapter, you should know enough about the syntax and semantics
of statements in Java to be able to write simple applications. But before we can talk about writ-
ing statements, we must understand how names are defined in Java and become familiar with
some of the elements of Java code.
Naming Program Elements: Identifiers
As we noted in our discussion of metalanguages, we use an identifierin Java to name some-
thing. For example, an identifier could be the name of a class, a subprogram (called a method
Import-Declaration;...
Class-Modifier...
Class-Declaration...
{
class Identifier
}
Package A named collection
of object classes in Java that can
be imported by a program
Class A definition for an object
or an application in Java
Identifier A name associated
with a package, class, method, or
field and used to refer to that
element
Method A subprogram in Java