Java Reference
In-Depth Information
Interface
Description
An interface used to identify classes whose objects can be written to (i.e., serialized)
or read from (i.e., deserialized) some type of storage (e.g., file on disk, database
field) or transmitted across a network. We use
Serializable
in Chapter 15, Files,
Streams and Object Serialization, and Chapter 28, Networking.
Serializable
Implemented by any class that represents a task to perform. Objects of such as class
are often executed in parallel using a technique called
multithreading
(discussed in
Chapter 23, Concurrency). The interface contains one method,
run
, which speci-
fies the behavior of an object when executed.
Runnable
GUI event-
listener
interfaces
You work with graphical user interfaces (GUIs) every day. In your web browser,
you might type the address of a website to visit, or you might click a button to
return to a previous site. The browser responds to your interaction and performs
the desired task. Your interaction is known as an
event
, and the code that the
browser uses to respond to an event is known as an
event handler
. In Chapter 12,
GUI Components: Part 1, and Chapter 22, GUI Components: Part 2, you'll learn
how to build GUIs and event handlers that respond to user interactions. Event
handlers are declared in classes that implement an appropriate
event-listener inter-
face
. Each event-listener interface specifies one or more methods that must be
implemented to respond to user interactions.
Implemented by classes that can be used with the
try
-with-resources statement
(Chapter 11, Exception Handling: A Deeper Look) to help prevent resource leaks.
AutoCloseable
Fig. 10.16
|
Common interfaces of the Java API. (Part 2 of 2.)
This section introduces Java SE 8's new interface features. We discuss these in more detail
in later chapters.
Prior to Java SE 8, interface methods could be
only
public
abstract
methods. This meant
that an interface specified
what
operations an implementing class must perform but not
how
the class should perform them.
In Java SE 8, interfaces also may contain
public
default
methods
with
concrete
default implementations that specify
how
operations are performed when an imple-
menting class does not override the methods. If a class implements such an interface, the
class also receives the interface's
default
implementations (if any). To declare a
default
method, place the keyword
default
before the method's return type and provide a con-
crete method implementation.
Adding Methods to Existing Interfaces
Prior to Java SE 8, adding methods to an interface would break any implementing classes
that did not implement the new methods. Recall that if you didn't implement each of an
interface's methods, you had to declare your class
abstract
.
Any class that implements the original interface will
not
break when a
default
method is added—the class simply receives the new
default
method. When a class imple-