Java Reference
In-Depth Information
Other Reference Types
The signature of a class may also declare that the class implements one or more
interfaces. An interface is a reference type similar to a class that defines method sig‐
natures but does not usually include method bodies to implement the methods.
However, from Java 8 onward, interfaces may use the keyword default to indicate
that a method specified in the interface is optional. If a method is optional, the
interface file must include a default implementation (hence the choice of keyword)
which will be used by all implementing classes that do not provide an implementa‐
tion of the optional method.
A class that implements an interface is required to provide bodies for the interface's
nondefault methods. Instances of a class that implement an interface are also instan‐
ces of the interface type.
m
g
O
Classes and interfaces are the most important of the five fundamental reference
types defined by Java. Arrays, enumerated types (or “enums”), and annotation types
(usually just called “annotations”) are the other three. Arrays are covered in
Chapter 2 . Enums are a specialized kind of class and annotations are a specialized
kind of interface—both are discussed later in Chapter 4 , along with a full discussion
of interfaces.
Class Deinition Syntax
At its simplest level, a class definition consists of the keyword class followed by the
name of the class and a set of class members within curly braces. The class key‐
word may be preceded by modifier keywords and annotations. If the class extends
another class, the class name is followed by the extends keyword and the name of
the class being extended. If the class implements one or more interfaces, then the
class name or the extends clause is followed by the implements keyword and a
comma-separated list of interface names. For example:
public class Integer extends Number implements Serializable , Comparable {
// class members go here
}
A generic class may also have type parameters and wildcards as part of its definition
(see Chapter 4 ).
Class declarations may include modifier keywords. In addition to the access control
modifiers ( public , protected , etc.), these include:
abstract
An abstract class is one whose implementation is incomplete and cannot be
instantiated. Any class with one or more abstract methods must be declared
abstract . Abstract classes are discussed in “Abstract Classes and Methods” on
page 128 .
Search WWH ::




Custom Search