简体   繁体   中英

using setter and getter for calculations

I have this program in Java that was working fine. However today, although there are no errors in the program, I get the following message:

Exception in thread "main" java.lang.NullPointerException
    at geometrycalculator.planeFigurePerimeter.rectangle(planeFigurePerimeter.java:12)
    at geometrycalculator.GeometryCalculator.main(GeometryCalculator.java:50)
C:\Users\gustavo\AppData\Local\NetBeans\Cache\8.2\executor-snippets\run.xml:53: Java returned: 1
BUILD FAILED (total time: 8 seconds)

So on line 12 of the child class I have:

calculator.setPerimeter((length + width) * 2);

On line 50 of the main program I have:

perimeter.rectangle();

On the parent class I have:

public void setPerimeter(double newPerimeter){
        perimeter = newPerimeter;
    }
    public double getPerimeter(){
        return perimeter;
    }

For some reason the calculation is not performing in: calculator.setPerimeter((length + width) * 2);

The parent class is abstract, the child class extends from the parent class, that way I don't have to create the same variables on all the other child classes.

The only possibility to get NPE is, your calculator object reference might not have initialized/ null .

Check if it has been initialized properly before calling setPerimeter method

calculator.setPerimeter((length + width) * 2);

Ok so the issue I was having was because I had the parent as the abstract class and couldn't access the setter and getter directly. I changed the parent class to be public and not abstract and it works now. Any suggestions on if I should change the parent class from public to private and/or have it be abstract are welcome. Im open to expand my knowledge on Java.

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