为什么我构造器中初始化lenght为1,但是我get lenght却为0


public class Cylinder extends Circle{
    private double length;
    
    public Cylinder() {
        double length = 1.0;
    }
    public void setLength(double length) {
        this.length = length;
    }
    public double getLength() {
        return length;
    }
    public double findVolume() {
        return findArea()*getLength();
    }
}

public Cylinder() {
double length = 1.0;
}
你这相当于在函数内定义了一个临时变量,而不是给类的成员变量length赋值,修改如下。

 
public class Cylinder extends Circle{
    private double length;
    
    public Cylinder() {
        length = 1.0;
    }
    public void setLength(double length) {
        length = length;
    }
    public double getLength() {
        return length;
    }
    public double findVolume() {
        return findArea()*getLength();
    }
}

要访问成员变量,函数内部定义的变量,其他方法不能访问,修改如下。


public Cylinder() {
        this.length = 1.0;
    }

img

您好,我是有问必答小助手,您的问题已经有小伙伴帮您解答,感谢您对有问必答的支持与关注!
PS:问答VIP年卡 【限时加赠:IT技术图书免费领】,了解详情>>> https://vip.csdn.net/askvip?utm_source=1146287632