简体   繁体   English

使用 setter 和 getter 进行计算

[英]using setter and getter for calculations

I have this program in Java that was working fine.我在 Java 中有这个程序运行良好。 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:所以在子 class 的第 12 行我有:

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

On line 50 of the main program I have:在主程序的第 50 行,我有:

perimeter.rectangle();

On the parent class I have:在父 class 我有:

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);由于某种原因,计算没有执行: 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.父 class 是抽象的,子 class 从父 class 扩展,这样我就不必在所有其他子类上创建相同的变量。

The only possibility to get NPE is, your calculator object reference might not have initialized/ null .获得 NPE 的唯一可能性是,您的calculator object 参考可能尚未初始化/ null

Check if it has been initialized properly before calling setPerimeter method在调用setPerimeter方法之前检查它是否已经正确初始化

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.好的,所以我遇到的问题是因为我将父级作为抽象 class 并且无法直接访问设置器和获取器。 I changed the parent class to be public and not abstract and it works now.我将父 class 更改为公共而不是抽象的,它现在可以工作了。 Any suggestions on if I should change the parent class from public to private and/or have it be abstract are welcome.欢迎任何关于我是否应该将父 class 从公共更改为私有和/或将其抽象化的建议。 Im open to expand my knowledge on Java.我愿意扩展我对 Java 的知识。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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