• Post Reply Bookmark Topic Watch Topic
  • New Topic

creating a reference for Interface  RSS feed

 
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In Java 1.5
we are creating a reference for Interface ,
for instance

Map<String,String> map = new HashMap<String,String>();
[Interface] [Class]


What is purpose?
In JVM how to handle in this situtation.


 
Ranch Hand
Posts: 128
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The reason is that you can have differend implementations of the interface, providing different functionalities, but still doing what it is expected by the interface contract. Eg. for Map you can have a HashMap, which is generally very fast (put/get), but is not ordered and requires a good hash function. If a really bad function is used, the map gets really slow. And you can have a TreeMap, which is ordered and the get/put operations always take the same amount of time (depending on the map's size), slower then the optimistic HashMap's variant, but faster than the pessimistic variant. Whichever you choose, they both fulfil the Map's contract of mapping keys to values. Using interfaces allows decoupling and lets you easily change the implementation from one to another if a need arises. For instance if you are using and interface of some sort and the implementation does some long-lasting operations or network access, for tests you can use another, mocked implementation of that interface and provide static data from a file.

In JVM there is a special command for invoking methods via interface - invokeinterface
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!