0

How the statement return new Enumeration() is possible, since Enumeration is an Interface. Plz explain. Thanks.

public Enumeration<E> elements() {
    return new Enumeration<E>() {
        int count = 0;

        public boolean hasMoreElements() {
            return count < elementCount;
        }

        public E nextElement() {
            synchronized (Vector.this) {
                if (count < elementCount) {
                    return elementData(count++);
                }
            }
            throw new NoSuchElementException("Vector Enumeration");
        }
    };
}
marcolopes
  • 9,232
  • 14
  • 54
  • 65
Dhruvam Gupta
  • 482
  • 5
  • 10
  • possible duplicate of [How are Anonymous (inner) classes used in Java?](http://stackoverflow.com/questions/355167/how-are-anonymous-inner-classes-used-in-java) – Joe Feb 14 '15 at 02:27

1 Answers1

0

It is possible because it implements the Enumeration interface through an anonymous inner class.

Interfaces are defined to be implemented, and the use of an anonymous inner class is simply a shortcut, that works the same way as when you instantiate an abstract class (you must implement the abstract methods). In this case, you must implement ALL of the interface methods.

marcolopes
  • 9,232
  • 14
  • 54
  • 65