Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cast a list of concrete type to a list of its interfaces in Java

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

like image 274
Caps Avatar asked Aug 19 '11 13:08

Caps


People also ask

Can an interface inherit from a concrete class?

A concrete class can implement multiple interfaces, but can only inherit from one parent class.

How many concrete classes are allowed inside an interface?

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.

What are the List interface methods?

The implementation classes of the List interface are ArrayList, LinkedList, Stack, and Vector. ArrayList and LinkedList are widely used in Java programming.


2 Answers

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;
    }
}
like image 127
aioobe Avatar answered Oct 06 '22 11:10

aioobe


If you really want to do this something like the below might work

@Override
public List<Shape> getShapes() {
   return new ArrayList<Shape>(squares); 
}
like image 39
Konstantin Avatar answered Oct 06 '22 13:10

Konstantin