How to use interface as parameter?

424 views Asked by At

I am using EJML and I want to use the class LinearSolver_B64_to_D64, which has the constructor: LinearSolver_B64_to_D64(LinearSolver<BlockMatrix64F> alg) with the interface LinearSolver<BlockMatrix64F> and the class has already implemented the LinearSolver.

What I know: In general you create a interface, than you would implement that interface in a specific class. I read about functions(in the specific class) that take the interface as a parameter, because that way your functions does not need to know something about the class.

My question: I don't know how to initialise the class LinearSolver_B64_to_D64, because I don't know how to pass an interface as a parameter.

Update: I tried the following code:

public class UseMatrixInterface{
    public UseMatrixInterface(){    
    }

    public void do1(){
        DenseMatrix64F a = new DenseMatrix64F(3,3);
        LinearSolver_B64_to_D64 ls = new LinearSolver_B64_to_D64(null); 

//it throws a nullpointer exeption. I assume, it is because i used null
//instead of the requiered parameter.
        ls.invert(a);
        a.print();
    }

    public void do2(){
        LinearSolver<BlockMatrix64F> lsD;
        LinearSolver_B64_to_D64 ls = new LinearSolver_B64_to_D64(lsD);
        //not working, because lsD cannot be initialised;
    }
}
3

There are 3 answers

2
GhostCat On

Just study javadoc; like starting here for the interface LinearSolver.

And guess what: there is a section

All Known Implementing Classes: AdjLinearSolverQr_D64, ...

Go and pick the one that matches your needs; and create an instance of that class.

So the answer to your question is: you can't instantiate interfaces. Instead you look out for classes implementing the interface, and then you create an instance of such a class. Like in:

List<String> strings = new ArrayList<>();
3
Timothy Truckle On
  • create an instance of a class that implements the interface. Most likely the interfaces contract (the the JavaDoc of the interface) is simple enough to do this as an anonymous inner class

    LinearSolver<BlockMatrix64F> alg = new LinearSolver<BlockMatrix64F>(){
      // implement interface method(s) here
    }   
    

then

  • pass that object to the constructor of LinearSolver_B64_to_D64()

    LinearSolver_B64_to_D64(alg);
    
0
lessthanoptimal On

Not really sure what's going on with this question and these answers. LinearSolver_B64_to_D64 is a low level class for converting a linear solver for block matrices into the standard DenseMatrix64F. You probably don't want to use that.

The Manual:

LinearSolverFactory is the preferred way to create a new LinearSolver and hides most of the low level details from you.