Reputation: 2095
We cannot create an instance of an interface.
But why does Arrays.asList(Object[] a)
in the Java API, return a List
(List
being an interface)?
Thank you!
Upvotes: 0
Views: 329
Reputation: 1029
Java and OOO programming in general lets you define how an object should be used (that´s the interface of the object) so only the library implementor needs to worry about the gory details of how things actually work. That´s why it is good practice to never return a class itself but just an interface, in addition to better maintanibility it will also let you use mocks or stubs objects when coding tests for your applications.
Java in particular let´s you create an interface implementation on fly. i.e you can do something like
return new List() { boolean add() {...} void addAll {...} ... }
This is of course an overkill for complex interfaces like List but actually very handy for smaller interfaces.
Upvotes: 2
Reputation: 887325
It creates an instance of a class which implements the interface.
You don't know what that class is; it could even use a different class every other Tuesday (it doesn't).
You just use the class through the interface.
Upvotes: 3