Re: Interface Delegation or ??
tam@milkyway.gsfc.nasa.gov wrote:
Ah, but they can now create their own implementation of the interface
and pass it in to some public method that takes the interface as an
input and thus get access to something they weren't able to get to
before... I.e.,
Lew wrote:
No previous implementation of the interface can have been passed to a
public method in a public class, since none of the type or its subtypes
were publicly visible. Your scenario cannot happen.
...
The actual interactions are precisely specified for Java.
If the public class is in the same package as the package-private interface,
it can get away with exporting the interface type via a public method.
While technically legal, it does raise a warning in my IDE. (NetBeans, as it
happens, but I'm pretty sure Eclipse supports this warning also.)
"Exporting non-public type through public API"
This pathological example does just that in the methods that set and get an
'InnerFace' instance. It makes 'Fimpl' a little difficult to use from outside
the package; the client code has to treat the signatures as though they used
'Object' instead of 'InnerFace' and they don't have access to the supertype,
specifically not to its methods. (Not through the supertype reference, at least.)
While this usage is barely legal, the best advice is not to do it. Don't
expose restricted visibility types to wider examination. If you make a type
package-private, it's for a reason. It's a type.
public class Fimpl implements Runnable
{
/** Keep the interface on the down-low.
*/
/* p-p */ static class NestedFimpl implements InnerFace
{
@Override
public void foo()
{
System.out.println( "NestedFimpl.foo()" );
}
}
private volatile InnerFace face;
/** No-arg constructor.
*/
public Fimpl()
{
this( null );
}
/* p-p */ Fimpl( InnerFace f )
{
face = (f == null? new NestedFimpl() : f);
}
/* p-p */ void setFace( InnerFace f )
{
face = (f == null? new NestedFimpl() : f);
}
/* p-p */ InnerFace getFace()
{
return face;
}
/** Delegate an action to <code>foo()</code>.
*/
@Override
public void run()
{
face.foo();
}
/** Expose the package-private interface to the whole world.
* @param f non-visible type, pass an <code>Object</code>.
*/
public void setInnerFace( InnerFace f )
{
setFace( f );
}
/** Expose the package-private interface to the whole world.
* @return non-visible type, treat as <code>Object</code>.
*/
public InnerFace getInnerFace()
{
return getFace();
}
}
--
Lew