首页 > 解决方案 > 带有继承的 Java 中的 NullPointerException

问题描述

我正在编写一个程序来模拟身体活动下的人体温度。我写了一个广泛的“隔间”类,如下所示:

public class compartment {

    public float height;
    public float weight;
    public float age;
    public float mrest;

    public float HR;
    public float VO2;
    public float [] temps;
    public float [] K = {54.29f, 41.76f, 15.87f, 41.76f, 20.88f};

    private float BF;
    private float T;
    private float H;

    private float hCap;
    private float dnsty;

    public compartment(float height, float weight, float age, float HR, float VO2, float [] temps) {

        height = this.height;
        weight = this.weight;
        age = this.age;
        mrest = 1.5f * weight;

        HR = this.HR;
        VO2 = this.VO2;
        temps = this.temps;
    }

    // GETTERS
    public float getBF() {
        return BF;
    }
    public float getT() {
        return T;
    }
    public float getH() {
        return H;
    }
    public float gethCap() {
        return hCap;
    }
    public float getDnsty() {
        return dnsty;
    }

    // SETTERS
    public void setBF(float BF) {
        BF = this.BF;
    }
    public void setT(float T) {
        T = this.T;
    }
    public void setH(float H) {
        H = this.H;
    }
    public void sethCap(float hCap) {
        hCap = this.hCap;
    }
    public void setDnsty(float dnsty) {
        dnsty = this.dnsty;
    }
}

然后我编写了一个子类,它是主体的核心隔间,如下所示:

public class core extends compartment{

    public void calc() {

        // Setting up constants
        int n = 0;
        float H = 0.824f;
        setDnsty(1.1f);
        sethCap(51);

        // Calculating blood flow
        float pctMaxHr = HR/(220-age);
        float dubois = (float) (2.0247 * Math.pow(height, 0.725) * Math.pow(weight, 0.425));
        float pctMaxBf = (float) ((pctMaxHr <= 39) ? 100:100 - 1.086*(pctMaxHr-39));
        float maxBf = (float) (0.92*dubois*3.2);
        float bf = (pctMaxBf)*(maxBf);

        // Calculating heat production
        setH(mrest*H);

        // Calculating derivative
        float Q = getH() - (K[n]*(temps[n] - temps[n+1])) - (bf*getDnsty()*gethCap()*(temps[n] - temps[5]));

        // Adjusting the temperature
        float T = temps[n] + Q;
        setT(T);
    }

    public core(float height, float weight, float age, float HR, float VO2, float[] temps) {
        super(height, weight, age, HR, VO2, temps);
        calc();
    }

}

但是,当我尝试创建一个“核心”对象时,我得到了 java NullPointerException

Exception in thread "main" java.lang.NullPointerException
    at core.calc(core.java:22)
    at core.<init>(core.java:32)
    at model.main(model.java:7)

第 22 行是行

float Q = getH() - (K[n]*(temps[n] - temps[n+1])) - (bf*getDnsty()*gethCap()*(temps[n] - temps[5]));

使用 System.out.println 进行一些调试,似乎没有一个变量正确实例化,例如,当我打印变量 mrest 或 height 时,它们都显示为 0.0

我错过了继承的基本属性吗?我究竟做错了什么?谢谢。

标签: javainheritance

解决方案


这是因为你做错了set价值分配。它应该this.dnsty = dnsty和其他人一样。(也是构造函数)


推荐阅读