basheer basheer - 1 year ago 102
Java Question

Calling an Instance Method of an Interface Directly

I am new to Java. Started a couple of weeks ago, relying on oracle documentation and this site. Gradually I am getting good understanding of OOP main concepts.

It is clear to me that an instance method of an interface becomes an instance method of the implementing class, and thus, can be called through an object of the implementing class, after being instantiated.

The interface Set has the method iterator(). To my understanding, we need to have a class that implements the Set interface first, then instantiate an object of that class, in order to be able to call that method (through the object).

Looking at the following code snippet, that I was reading online, I noticed that the iterator() method is called through (set) which is of the type (Set interface) only, (i.e set is not an instance of any class that implements Set interface).

My question is: is this possible?

On the other hand, regardless of whether the above is possible or not, according to oracle documentation, the method iterator() is categorized as an "instance" and "abstract" method for the Set interface. So, how come it is called for the "set" variable, since only default and static interface methods have implementations ?

public static void main(String args[]) {

HashMap<Integer, String> hmap = new HashMap<Integer, String>();

hmap.put(12, "Chaitanya");
hmap.put(2, "Rahul");

/* Display content using Iterator*/
Set set = hmap.entrySet();
Iterator iterator = set.iterator();
while(iterator.hasNext()) {
Map.Entry mentry = (Map.Entry);
System.out.print("key is: "+ mentry.getKey() + " & Value is: ");

Answer Source

Here is how to read this:

Set set = hmap.entrySet();
Iterator iterator = set.iterator();

hmap.entrySet returns an object into the set variable that implements the Set interface. That means set implements all of the methods declared in the Set interface. It is therefore perfectly fine to call the iterator() method against the set object, since it is one of the methods of the Set interface.

set is an object that implements the Set interface. It is not an interface. The only interface here is Set.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download