When defining "Set set = new HashSet ()", an instance of the interface or the Set class is specified?

In Java, "Set" and "List" are interfaces derived from the "Collection" interface. If we use the code:

import java.util.*; public class SetExample{ public stactic void main(String[] args){ Set set = new HashSet(); //do something ..... } } 

Is there a class 'Set' in the API 'Collection' that we create for the object ('set')? or are we creating the "Set" interface?

I'm really confused .......: O

+4
source share
5 answers

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.)

+11
source

Here are a few pointers:

You should also read Effective Java from Joshua Bloch , especially paragraph 52: “Access objects by their interfaces” (There is a small fragment visible here )

+4
source
Interface

java.util.Set provides free communication with the java.util.HashSet object. Therefore, the developer can use the java.util.Set link for another family object of the java.util.Set interface.

+1
source

The set reference is of type java.util.Set , which is an interface . Although in fact this points to an object of type java.util.HashSet . (Polymorphic)

0
source

In the API, you get a bunch of interfaces that hide the implementation. for example, the Set allows you to hide any implementation for which the HashSet is one of.

0
source

All Articles