Genric cast from impl to interface
I have an interfaceABCInterface
and an implementationACBImpl
I want to write a method which will return a set of ABCImpl in form of ABCInterface, how can I do that using generics.
publicclass ABCHelper{
Set<ABCImpl> abcs =new HashSet<ABCImpl>();
public Set<ABCInterface > getABCs(){
return abcs;
}
}
the above program will give me a cannot cast error while compiling.
How to solve this problem.
TIA
Shajee
# 1
You wil have to return "Set<? extends ABCInterface>", as a Set<ABCImpl> is no Set<ABCInterface>.
Simple example:
interface Animal {}
class Dog implements Animal {}
class Cat implements Animal {}
Set<Dog> dogs = new HashSet<Dog>();
Set<Animal> animals = dogs; // BAD
animals.add(new Cat());
If the BAD line would be possible (which is similar to your getABCs()), you could add a Cat to the set of Dogs.
# 2
Define your set like this:Set<ABCInterface> abcs = new HashSet<ABCInterface>();
abcs.add(new ABCImpl()); // you can add ABCImpl instances in it
// ...
or rename you method like this:public Set<? extends ABCInterface> getABCs() {
// ...
}
Edit: man I'm slow...