I am learning Java, I saw the following description regards to interface in a book:
When a variable is declared to be of an interface type, it simply
means that the object is expected to have implemented that interface.
What does it mean? If I define an interface:
public interface Myinterface{
void method_one();
int method_two();
}
Then, I declare a variable to be of an interface type for example:
Myinterface foo = new Myinterface();
- How the interface get implemented??
- Under what circumstance I should define a interface type variable?
I completely get confused by the book’s description…
You cannot instantiate an interface, i.e. you cannot do
What you can do is instantiate a class that implements the interface. That is, given a class
MyClassyou can instantiate it and place a reference to it in your variable like this:
If you had another class implementing
MyInterfaceyou can also substitute a reference to this class’s instance under your variable:
This is where the power of interfaces lies: they define types, not a particular implementation and let you refer to any implementation of a given type.
It is a very good programming practice to make classes implement interfaces and to use these to refer to instances of these classes. This practice facilitates a great deal of flexibility and reuse.
Therefore, you should use interface type arguments and variables whenever it is conceivable that different implementations may be passed into the method you’re implementing. For example, if you’re working with a
HashSet<T>instance, you should use a variable of typeSet<T>to refer to it (classHashSet<T>implements interfaceSet<T>).