Here is the scenario:
Set<Map.Entry<String,Integer>> st=hashMap.entrySet();
for(Map.Entry<String,Integer> me : set)
{
System.out.println(me.getKey()+":"+me.getValue());
}
Now my question is if Set,Map,Entry all are interfaces and getKey() and getValue() are the methods inside Entry interface how can Map.Entry call them without creating object ?
Extending my commet to the answer :
The basic idea is Expose the interface hide the implementation . Usually method return type is the Interface and from in side of the method hidden implementation is returned. This keeps the users of such code (libs) decoupled from implementation. Implementating class can change without the users being affected.
Now your query about
Set<String,Integer> st=hashMap.entrySet();
HashMap source code has a inner class which implements Set. The method entrySet() is present in HashMap which returns an object of that class which implements Set. The return type in the signature is Set and not that implementing class, but it is the object of the concrete class implementing the Set interface that is returned.
This way authors of HashMap.java have hidden the implementation from you. They can at their will change the implementing class in new versions of Java. Only they need to take care that their new implementing class implements Set interface.
It is similar to below code.
public interface InterfaceExposed{
public void task();
}
public class A{
private class Implementation implements InterfaceExposed{
public void task(){
// some code to do task as per current implementation.
}
}
public IExposedInterfaceOfA similarToEntrySet(){
return new Implementation();
}
}
Now users of class A will be dependent upon exposed interface and will not know and not depend on hidden private Implementation.
A a = new A();
IExposedInterfaceOfA xyz = a.similarToEntrySet();
xyz.task();
Here you see xyz as being of type IExposedInterfaceOfA but it refers to object of Concrete class Implementation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With