4

In Java, 'Set' and 'List' are interfaces derived from '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 "Collection" API that we are creating an object ('set') of? or we are instantiating a interface 'Set'?

Am really confused.......:O

Sean Patrick Floyd
  • 292,901
  • 67
  • 465
  • 588
Annibigi
  • 5,895
  • 5
  • 23
  • 21

5 Answers5

12

java.util.Set is an interface, not a class. So

Set set = new HashSet();

creates an object that is a HashSet instance, and assigns a reference to that object to a variable whose type is 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 an interface.

An Java interface is essentially a contract between an implementation (a class) and the things that use it. It says what the names and signatures of a conforming object's methods are, but nothing about the object's state or how its methods work.

(Just to confuse things a bit ... Java also allows you to write something like this:

Set set = new Set() {
    // attributes and methods go here
};

This is does not create an "instance" of the Set interface per se ... because that doesn't make sense. Rather, it declares and instantiates an anonymous class that implements the Set interface.)

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
  • I came here to find out the difference between `Set set = new HashSet();` vs `HashSet set = new HashSet();`. So is there a difference? – Madmenyo Jul 03 '15 at 15:43
4

Here are some pointers:

You should also read Effective Java by Joshua Bloch, especially item 52: "Refer to objects by their interfaces" (There's a small snippet viewable here)

Sean Patrick Floyd
  • 292,901
  • 67
  • 465
  • 588
1

java.util.Set interface provides the loose coupling with java.util.HashSet object. So developer can use the java.util.Set reference for another java.util.Set interface family object.

Aman Gupta
  • 5,548
  • 10
  • 52
  • 88
Balaji V
  • 11
  • 1
0

The reference set is of type java.util.Set which is an interface. Although it actually points to an object of type java.util.HashSet. (polymorphic)

Rahul
  • 19,744
  • 1
  • 25
  • 29
0

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

Gadolin
  • 2,636
  • 3
  • 28
  • 33