Re: Separate interface and implemenation problem..
On Thu, 4 Jun 2009, Patricia Shanahan wrote:
Lew wrote:
MRe wrote:
It would be nice if Java allowed protected (or private) modifiers
inside an interface [why doesn't it?]
In addition to what Eric wrote (infra), it would, a), violate the
definition of 'private', and, b), violate the definition of an
interface.
By design, 'private' means "that which the outside world should not
ever know". By design, an interface publishes "exactly what the
outside world must know". They are exact opposite concepts.
...
I agree that "private" does not make sense for interfaces. However, I
would have uses for default access.
I quite often have a group of classes that present one interface to the
whole of the program, and additional features to the rest of the package
in which they appear. For example, a "get" method might be public, but
the corresponding "set" method package-only. I would love to be able to
define the package-only methods in a package-only interface.
You can get an effect along these lines by having separate public and
package interfaces:
public interface Body {
public Organ getEye();
public Organ getEar();
}
/*package*/ interface BodyInternal extends Body {
public Organ getSpleen();
}
/*package*/ class RobotBody implements BodyInternal {
public Organ getSpleen() {
return new RobotSpleen();
}
// etc
}
As long as you only ever expose Bodies typed as Body, not as any specific
implementing class (for instance, by making those classes package-access,
as i have above), then getSpleen() will never be visible outside the
package. Of course, this does impose quite enormous restrictions on what
you can do with your classes, which might make the whole thing not worth
it.
Another point is that if you have a public method which returns Body, it
has to return Body not BodyInternal, which means either internal users
will have to cast to get a BodyInternal, or you have to have a
package-access shadow method which returns BodyInternal. Both are lame.
tom
--
It involves police, bailiffs, vampires and a portal to hell under a
tower block in Hackney.