Reputation: 33243
I am a newbie in java and I am trying to implement an interface.
So main class
public interface Matrix{
//returns number of rows
int numRows();
//returns number of columns
int numColumns();
int addRows(...);
....
}
Now basically what I am trying to solve is lets say.. I have two matrices matrixa
and matrixb
of type Matrix
.
I want to basically extend the matrix row wise.
So if matrixa
had 10 rows and matrixb
has 2 rows.
Then I want to return matrixa+=matrixb
(offcourse assuming that number of columns are same.)
What is the right way to do this?
Upvotes: 2
Views: 993
Reputation: 11433
Java has no operator overloading. You can not use +=
with your objects.
It is generally believed in java world that operator overloading decreases readablility.
However you can use methods such as addMatrix(Matrix m)
.
public interface Matrix{
int getNumberOfRows();
int getNumberOfColumns();
Matrix addMatrix(Matrix m);
}
Upvotes: 1
Reputation: 8269
To implement an interface you create a class that implements the interface and all of it's methods.
public class MatrixImpl implements Matrix{
private List<List<Integer>> elements = new ArrayList<List<Integer>>();
private int rowSize;
...
/** appends rows from provided matrix to this matrix */
public Matrix addRows(Matrix b){
List<List<Integer>> rows;
if (b == this){
rows = new ArrayList(b.elements);
}else {
rows = b.elements;
}
for (List<Integer> row : rows){
if(row.size() == rowSize){
elements.add(new ArrayList(row));
}else{
// do some error handling
}
}
return this;// you may want to return a clone instead
}
...
}
Upvotes: 0
Reputation: 4298
The easy answer is: you implement an interface by reading this http://docs.oracle.com/javase/tutorial/java/IandI/usinginterface.html
I would start with java tutorials since you are a beginner. You can't instantiate an interface, an interface (typically) only contains method header definitions. The way you use interfaces is you implement them by creating a normal java class that implements code for each of the methods found in the interface.
Btw, I would highly recommend reading tutorials rather than relying on SO for questions like this.
Upvotes: 0
Reputation: 21902
I'm trying to make sense of the question. I think what you are trying to do is define:
int addRows(Matrix b);
In that method implementation, you would:
All of this implementation is dependent on how you implement the Matrix interface.
Upvotes: 0
Reputation: 68962
You could add another method to your interface like:
public interface Matrix{
....
Matrix add( Matrix b );
}
and check for the necessity to expand rows in the implementation.
Upvotes: 6