Reputation: 21
I got this method to multiply 2 matrices:
public static AbstractMatrix multiplication(AbstractMatrix m1, AbstractMatrix m2) {
AbstractMatrix result = null;
int sum=0;
if (m1.getNbc() == m2.getNbl()) {
for(int c=0;c<m1.getNbl();c++){
for(int d=0;d<m2.getNbc();d++){
for(int k=0;k<m1.getNbc();k++){
sum=somme+m1.getValeur(c, k)*m2.getValeur(k, d);
}
result.setValeur(c, d, sum);
sum=0;
}
}
}
return result;
}
I am getting a:
null pointer access the variable result can only be null
at this location: result.set()
. I know that the problem is in AbstractMatrix result=null;
but AbstractMAtrix
is an abstract class so I can't instantiate it (new AbstractMatrix
).
How can I fix this?
Upvotes: 1
Views: 210
Reputation: 15320
You correctly identified your problem -> you are trying to call a method on null
which obviously cannot be done.
Also, you correctly identified that AbstractMatrix
is an abstract
class and therefore cannot be instantiated.
What needs to be done to remedy this?
You must create a subclass, let's say Matrix extends AbstractMatrix
which overrides any abstract
methods in AbstractMatrix
. Then you may instantiate it like so:
AbstractMatrix result = new Matrix();
This will make your code run correctly and will not throw an NPE.
Upvotes: 1