Java Reference
In-Depth Information
public class GreetingImpl implements Greeting {
final String m_name;
public GreetingImpl(String name) {
m_name = name;
}
public void sayHello() {
System.out.println("Hello, " + m_name + "!");
}
}
C
Interface
implementation
package org.foo.hello.main; Main.java
import org.foo.hello.Greeting;
import org.foo.hello.impl.GreetingImpl;
public class Main {
public static void main(String[] args) {
Greeting greet = new GreetingImpl("Hello World");
greet.sayHello();
}
}
Listing 1.1's author may have intended a third party to only interact with the application
via the Greeting interface B . They may mention this in Javadoc, tutorials, blogs, or even
email rants, but nothing stops a third party from constructing a new GreetingImpl using
its public constructor C as is done at D .
You may argue that the constructor shouldn't be public and that there is no need
to split the application into multiple packages, which could well be true in this trivial
example. But in real-world applications, class-level visibility when combined with pack-
aging turns out to be a crude tool for ensuring API coherency. Because supposedly pri-
vate implementation details can be accessed by third-party developers, you need to
worry about changes to private implementation signatures as well as to public inter-
faces when making updates.
This problem stems from the fact that although Java packages appear to have a log-
ical relationship via nested packages, they don't. A common misconception for people
first learning Java is to assume that the parent-child package relationship bestows spe-
cial visibility privileges on the involved packages. Two packages involved in a nested
relationship are equivalent to two packages that aren't. Nested packages are largely
useful for avoiding name clashes, but they provide only partial support for the logical
code partitioning.
What this all means is that, in Java, you're regularly forced to decide between the
following:
1 Impairing your application's logical structure by lumping unrelated classes into
the same package to avoid exposing nonpublic API s
2 Keeping your application's logical structure by using multiple packages at the
expense of exposing nonpublic API s so they can be accessed by classes in differ-
ent packages
Neither choice is particularly palatable.
D
Main
method
 
Search WWH ::




Custom Search