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
java.util.Setis an interface, not a class. Socreates an object that is a
HashSetinstance, and assigns a reference to that object to a variable whose type isSet. This works because theHashSetclass implements theSetinterface. On the other hand: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:
This is does not create an “instance” of the
Setinterface per se … because that doesn’t make sense. Rather, it declares and instantiates an anonymous class that implements theSetinterface.)