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 typ
You cannot instantiate an interface, i.e. you cannot do
MyInterface foo = new MyInterface(); // Compile-time error.
What you can do is instantiate a class that implements the interface. That is, given a class MyClass
public class MyClass implements MyInterface {
// ...
@Override
void method_one() {
// ...
}
@Override
int method_two() {
// ...
}
}
you can instantiate it and place a reference to it in your variable like this:
MyInterface foo = new MyClass();
If you had another class implementing MyInterface
class MyClass2 implements MyInterface {
// ...
}
you can also substitute a reference to this class's instance under your variable:
MyInterface foo = new MyClass2();
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
instance, you should use a variable of type Set
to refer to it (class HashSet
implements interface Set
).