It's called "programming to an interface"
If you write "HashSet x = new HashSet();",
and your functions all take "HashSet" as arguments... then you have 2 problems:
1) What if later you decide that it is more efficient to use a different set (eg. TreeSet)?
You would have to rename your code all over the place.
2) What if you accidentally begin to rely on HashSet-specific methods?
(that is, methods that only HashSet has, but no other Set has).
Then later, if you want to change to something like TreeSet which doesn't have that method,
then you may have to do major rewrite of your code
such that it can work without that specific function!
Another way to put it is: chances are your code only cares that it is a Set.
Chances are your code doesn't care that it is a "HashSet".
So... it is logically preferred to reduce your dependency as much as possible.
> might sound very silly,but what if there are methods
> which are supported by Hashset and not SET?
Indeed there may be methods that are only in HashSet and not in Set.
And if you really, really need to use such a method, then yes, you should write HashSet x = new HashSet();
> how the assignment is possible
> Set setRef = new HashSet();
The assignment is LEGAL because you are assigning a more-specific object to a less-specific variable.
class A { }
class B extends A { }
A variable1 = new A(); // Legal
B variable2 = new B(); // Legal
A variable3 = new B(); // Legal, since B is a subclass of A
B variable4 = new A(); // Illegal
> might sound very silly,but what if there are methods
> which are supported by Hashset and not SET?
> how the assignment is possible
> Set setRef = new HashSet();
>
> sorry..but could you please elaborate?
then you'd dereference it as a HashSet. if you find you need to do so, it may be you have a design problem, though. the whole point is to abstract and generalize away from concrete implementations
> > might sound very silly,but what if there are
> methods
> > which are supported by Hashset and not SET?
> > ...
>
> Then you should use the concrete implementation of
> the hash set:HashSet mySet = new
> HashSet();
or, alternatively, you can assign multiple references to the same object, using Set wherever possible, and HashSet for the corner case when you need the concrete class
Set mySet = new HashSet();
// do stuff
// oops, I wish mySet was a HashSet, I need a method on it
HashSet hashSet = (HashSet) mySet;
// etc
in your example, though, there are no public methods on HashSet that aren't declared either in java.lang.Object or java.util.Set, so there wouldn't be any need to dereference as a HashSet. generally, if an API provides you with interfaces, there's seldom a need for concrete references. the interface simply declares all the public methods you'd ever need from the class