Jean-Benoit MORLA said:
Hi
Given this interface:
public interface Buffer{
public void set( int value );
public int get();
}
( compiles ok )
How come this compiles?:
public class Producer extends Thread {
private Buffer sharedLocation; // reference to shared object
.
.
I thought that if I wanted to use an interface I had to "implement" it
and declare all its methods.
Your confusion appears to arise from what it means to you to "use" an
interface. You would perhaps be better off to drop the term altogether
in favor of more specific language:
(1) A class may implement an interface. That means the class asserts
that it provides implementations for zero or more of the methods
declared by the interface, but more importantly, declares that the class
is a subtype of the interface. The class need not provide
implementations for all the interface's methods; if it does not do so,
however, then it must declare itself abstract. The class cannot declare
methods that conflict with those defined by the interface. The compiler
checks all these constraints.
(2) A class may declare variables, method arguments, and / or method
return values to have the interface for their type. Indeed, this is key
to making interfaces useful. A class that does these things is not
thereby required to implement the interface -- rather, the objects
stored, passed, or returned must be of classes that implement the
interface. (Technically it is the objects' references that are stored,
passed, or returned, not the objects themselves; consider the above to
be a simplification employed for purposes of prose clarity.)
(3) A class may transiently handle expressions whose declared type is an
interface, without explicitly naming the interface anywhere. E.g.:
[...]
o.doSomethingImportant(p.returnsAnInterfaceType());
[...]
where the declared return type of returnsAnInterfaceType() is, as the
name indicates, an interface, and the required type of the argument to
doSomethingImportant() is either Object or a compatible interface type.
There are no special constraints on that situation beyond the normal
Java type compatibility rules.
I hope that helps.
John Bollinger
(e-mail address removed)