0

I know that we cannot instantiate an interface. HashMap method, keySet(), its return type is Set.

public class aMap{
    public static void main(String args[]) {
        HashMap newmap = new HashMap();
        newmap.put(1, "please");
        newmap.put(2, "help");
        newmap.put(3, "me");
        System.out.println("Key set values are: " +        
        aMap.keySet());
    }    
}

Output: Key set values are: [please, help, ma]

-Why can the method return a Set, which is a interface?(if Set cannot instantiate)

-Suppose Set interface can only have static final attributes and empty methods, why can it (stores) Strings into a Set?

Bailey Lee
  • 21
  • 2
  • The method `keySet()` declares to return a `Set`, which is indeed an interface. But internally, it creates a concrete instance of a class that implements `Set`. But this is rightfully hidden from you, forcing you to develop against the interface. See the linked question. – Tunaki Apr 14 '16 at 12:37
  • 1
    Because it points to an implementation, this is polymorphism in action. All you're guaranteeing is the implementation is a type of Set (implements the interface) – MadProgrammer Apr 14 '16 at 12:37
  • It just means that method will return instance of *some* class which implements Set. Because of this flexibility implementation can be later changed so map can even return instance of *different* class implementing Set (which is helps very much, because only constant thing in our world is change). You should probably read about polymorphism. – Pshemo Apr 14 '16 at 12:37
  • A vehicle is something fairly abstract. It can be a bike, a car, a bus or whatever. Even though a vehicle is something abstract, you can give me a vehicle. For instance by giving me a car. The same thing is going on here. `keySet` gives you a `Set`, but it will in fact give you an actual implementation, such as a `HashSet` (or some other implementation). – aioobe Apr 14 '16 at 12:39
  • `"Why can the method return a Set"` - Because `Set` is a valid type. `"Set cannot instantiate"` - Where is anything trying to directly *instantiate* a `Set`? It's not happening in the code provided. – David Apr 14 '16 at 12:42

0 Answers0