为什么我的 setter 没有在我的 Java 程序中工作?

问题描述 投票:0回答:1

我的质量设置器确实成功地防止了变量在主方法中直接设置为负数,但它也允许构造函数用负值实例化对象,但事实不应该是这样。我尝试在构造函数中调用 setter,但它仍然允许设置负值。

public class Fly {
    // instance variables
    private double mass;
    private double speed;

    // static constants/variables
    public static final double defaultMass = 5.0;
    public static final double defaultSpeed = 10.0;
    
    // constructor methods
    public Fly() {
        this(defaultMass);
    }

    public Fly(double mass) {
        this(mass, defaultSpeed);
    }

    
    public Fly(double mass, double speed) {
        setMass(mass);
        setSpeed(speed);
    }
    
    // getters and setters
    public double getMass() {
        return mass;
    }

    public double getSpeed() {
        return speed;
    }
    
    public void setMass(double newMass) {
        if (newMass >= 0.0) {
            this.mass = newMass;
        }
    }

    public void setSpeed(double newSpeed) {
        if (newSpeed >= 0.0) {
            this.speed = newSpeed;
        }
    }

    // test method
    public static void main(String[] args) {
        Fly fly1 = new Fly();
        Fly fly2 = new Fly(-1.0);
        Fly fly3 = new Fly(6.0, 11.0);
        
        System.out.println(fly1.toString());
        System.out.println(fly2.toString());
        System.out.println(fly3.toString());

        fly3.grow(2.0);
        System.out.println(fly3);
        
        fly3.setMass(-1.0);
        System.out.println(fly3.getMass());
    }
}
java setter
1个回答
0
投票

当我运行它时,代码按预期工作(尽管我必须注释掉对

fly3.grow(2.0);
的调用)。

我添加了这个

toString
方法:

    @Override
    public String toString() {
        return "Fly{" +
                "mass=" + mass +
                ", speed=" + speed +
                '}';
    }

当我运行代码时,这是输出:

Fly{mass=5.0, speed=10.0}
Fly{mass=0.0, speed=10.0}
Fly{mass=6.0, speed=11.0}
Fly{mass=6.0, speed=11.0}
6.0
© www.soinside.com 2019 - 2024. All rights reserved.