Is there a way to cast a list of concrete types to a list of its interfaces in Java?
For example:
public class Square implements Shape { ... }
public SquareRepository implements Repository {
private List<Square> squares;
@Override
public List<Shape> getShapes() {
return squares; // how can I return this list of shapes properly cast?
}
}
Thanks in advance,
Caps
A concrete class can implement multiple interfaces, but can only inherit from one parent class.
Interfaces cannot have any concrete methods. If you need the ability to have abstract method definitions and concrete methods then you should use an abstract class.
The implementation classes of the List interface are ArrayList, LinkedList, Stack, and Vector. ArrayList and LinkedList are widely used in Java programming.
If you're in control of the Repository
interface, I suggest you refactor it to return something of the type List<? extends Shape>
instead.
This compiles fine:
interface Shape { }
class Square implements Shape { }
interface Repository {
List<? extends Shape> getShapes();
}
class SquareRepository implements Repository {
private List<Square> squares;
@Override
public List<? extends Shape> getShapes() {
return squares;
}
}
If you really want to do this something like the below might work
@Override
public List<Shape> getShapes() {
return new ArrayList<Shape>(squares);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With