Re: interfaces
babis85@gmail.com wrote:
Hello, i have a basic question as to the way of using interfaces.
Let's say that we have an interface In1.
Why is it valid to declare a variable of type In1?
For the same reason you can declare a variable of type
Class1. Remember, the variable is not an object instance but
a reference to an instance. When you write `Class1 cref;' you
create a reference variable that can point at any object that
is an instance of Class1 or one of its subclasses. When you
write `In1 iref;' you create a reference variable that can
point at any object of any class that implements In1.
Why is it valid to call an unimplemented method of the interface?
>
I mean, what for, there isn't a code to execute.
The method code exists, but not in the interface definition.
The class that implements In1 provides code for all the methods
In1 describes. When you write `iref.answer(42)' you are calling
a method of the object that iref points to.
Think of the interface as a "contract." The interface
definition describes some methods, and each class that implements
the interface provides implementations of those methods. If the
class doesn't provide all the methods, Java will not allow it to
claim `implements In1' and will not allow you to point iref at
its instances. On the other hand, if the class does in fact
implement all the interface's methods, Java permits it to declare
that it `implements In1' and permits you to use iref to refer to
its objects. Since the class implements In1, Java knows that it
has an `answer(int)' method even though it might not know at
compile time exactly what class iref points to -- anything it
can point to must necessarily have an `answer(int)' method.
--
Eric Sosman
esosman@acm-dot-org.invalid