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. But you may type your variable with the interface name:
Myinterface foo = new MyObject();
Assuming MyObject
implements MyInterface
.
It may be useful when acquiring objects from an external source, for instance.
In such a case, you don't know (and don't care) about the real type of the object.
You only need to know and ensure it implements some interface, so you can call interface methods on the object.
Assuming you have the following variable:
Myinterface foo;
And two classes (Foo
and Bar
), both implementing MyInterface
.
You will then be able to assign the foo
variables with instances of both Foo
and Bar
.
The same applies to methods arguments, of course.