Java Reference
In-Depth Information
Suppose each department must submit a job every day, even if they do not have something to run. It suggests
that sometimes you need an empty job or a job with nothing real to do. The developer of the
Job
interface may
provide a constant, which represents a trivial implementation of the
Job
interface as listed in Listing 17-15. It has a
nested class called
EmptyJob
, which implements the enclosing
Job
interface.
Listing 17-15.
The Job Interface with a Nested Class and a Constant Field
// Job.java
package com.jdojo.interfaces;
public interface Job {
// A nested class
class EmptyJob implements Job {
private EmptyJob() {
// Do not allow outside to create its object
}
public void runJob() {
System.out.println("Nothing serious to run...");
}
}
// A constant field
Job EMPTY_JOB = new EmptyJob();
// An abstract method
void runJob();
}
If a department does not have a meaningful job to submit, it can use
Job.EMPTY_JOB
constant as a job. The fully
qualified name of the
EmptyJob
class is
com.jdojo.interfaces.Job.EmptyJob
. Note that the enclosing interface
Job
provides an additional namespace for the
EmptyJob
class. Inside the
Job
interface, the
EmptyJob
class can be referred
to by its simple name of
EmptyJob
. However, outside the
Job
interface, it must be referred to as
Job.EmptyJob
. You
may notice that a trivial job object is represented by the
Job.EMPTY_JOB
constant. You have made the constructor for
the
EmptyJob
nested class private, so no one outside the interface can create its object. Listing 17-16 shows how to use
the class. Typically, in such cases, you would make the constructor of the
Job.EmptyJob
class
private
so its object
cannot be created outside the
Job
interface because the
EMPTY_JOB
constant already provides an object of this class.
Listing 17-16.
A Test Program to Test the Job Interface and Its Nested EmptyJob Class
// JobTest.java
package com.jdojo.interfaces;
public class JobTest {
public static void main(String[] args) {
submitJob(Job.EMPTY_JOB);
}
public static void submitJob(Job job) {
job.runJob();
}
}
Nothing serious to run...