简体   繁体   中英

Null pointer access

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM