Java 7 for Absolute Beginners

(nextflipdebug5) #1

CHAPTER 2 ■ JAVA SYNTAX


package. Other folks use a wildcard whenever they have just two members of the same package. Still
other developers never use wildcards because wildcards prevent you from seeing which objects are
actually used.

Abstract Classes


The class line identifies this particular class. Don't forget that the file that holds the class must have the
same name as the class, including the same capitalization.

public class AverageImpl extends Object implements Average {

All classes extend some other class. However, when a class extends Object (which is Java's root
object), you can omit extends Object. As we mentioned before, software developers are by nature
minimalists; we don't write anything that doesn't help. Consequently, few Java developers include the
extends keyword when the class being extended is Object.
Let's pick apart that class declaration and see what all the pieces mean. The first word, public,
is the access modifier for this class. See "Access Modifiers" later in this chapter, for more detail.
The second word, class, indicates that we define a class. In other words, we define a kind of object
that can be created in the system. In that case, we define a class that will never be an actual object.
Abstract classes are used for other classes to extend and as references. If this class were abstract, its
syntax would be as follows:

public abstract class AverageImpl extends Object implements Average {

Classes can also be static. On a class, the static keyword means that only one instance of that class
exists. You can't create a new instance of a static class (but the runtime engine creates one for you). As
an aside, you might find it interesting to know that a static class can still be cloned, so the static keyword
by itself does not guarantee a singleton (a class that has exactly one instance).

■ Note The alternative to defining a class is defining an interface. We get to interfaces later in this chapter.

The third word, AverageImpl, is the name of the class. Java has only two rules about class (and other
names). Each name must start with a letter. Each name must consist of only certain characters: a-z, A-Z,
0-9, and the underscore (_) and dollar sign ($) characters.

■ Note Impl is short for implementation, by the way. It's a fairly common practice to have an interface and a
class that provides an implementation for that interface. In those cases, a common naming convention is to name
the class with the name of the interface plus Impl. Don't worry, we get to what "implementation" means in the
"Interfaces" section.

In addition to the actual rules, the Java community follows certain customary guidelines for naming
classes.
Free download pdf