java.util.Set is an interface, not a class. So
Set set = new HashSet();
creates an object that is an instance of HashSet , and assigns a reference to this object to a variable of type Set . This works because the HashSet class implements the Set interface. On the other hand:
Set set = new Set();
gives a compilation error because you cannot create an instance of the interface.
The Java interface is essentially a contract between an implementation (class) and things that use it. It shows the names and signatures of the methods of the corresponding objects, but nothing about the state of the object and how it works.
(Just to confuse a little ... Java also allows you to write something like this:
Set set = new Set() { // attributes and methods go here };
This does not create an “instance” of the Set interface as such ... because it does not make sense. Rather, it declares and instantiates an anonymous class that implements the Set interface.)
source share