调用方法时更改变量

时间:2018-06-10 18:48:32

标签: java

我到处搜索,似乎无法找到答案。我试图在每次调用一个方法时增加一个变量,但它似乎正在重置变量并且只增加一次。这是我的代码。因此,每次创建类型为Bicycle的新对象时,对象都是更改bicycleCount构造函数以将{1}添加到Bicycle。我遇到的问题是它每次都重置为0,因此我为每个自行车创建了Bike 1。

class BicycleDemo {
    public static void main(String[] args) {

        // Create two instances each of MountainBike and RoadBike.
        Bicycle bike1 = new Bicycle.MountainBike();
        Bicycle bike2 = new Bicycle.MountainBike();
        Bicycle bike3 = new Bicycle.RoadBike();
        Bicycle bike4 = new Bicycle.RoadBike();

        // Invoke methods on those objects
        bike1.changeCadence(50);
        bike1.speedUp(10);
        bike1.changeGear(2);
        System.out.println("Bike: " + bike1.getbicycleCount());
        bike1.printStates();

        bike2.changeCadence(50);
        bike2.speedUp(10);
        bike2.changeGear(2);
        bike2.changeCadence(40);
        bike2.speedUp(10);
        bike2.changeGear(3);
        System.out.println("Bike: " + bike2.getbicycleCount());
        bike2.printStates();
    }
}
// Change the Bicycle class to be an abstract class.
abstract class Bicycle {
    /* Add a private variable of type integer named bicycleCount, and initialize
    this variable to 0.*/
    private static int bicycleCount=0;
    int cadence = 0;
    int speed = 0;
    int gear = 1;

    /* Change the Bicycle constructor to add 1 to the bicycleCount each time a
    new object of type Bicycle is created. */
    Bicycle() {
        bicycleCount++;
    }



    // Add a public getter method to return the current value of bicycleCount.
    public int getbicycleCount() {
        return bicycleCount;
    }

    void changeCadence(int newValue) {
        cadence = newValue;
    }

    void changeGear(int newValue) {
        gear = newValue;
    }

    void speedUp(int increment) {
        speed = speed + increment;
    }

    void applyBrakes(int decrement) {
        speed = speed - decrement;
    }

    void printStates() {
        System.out.println("cadence:" +
                cadence + " speed:" +
                speed + " gear:" + gear);
    }

    /* Derive two classes from Bicycle: MountainBike and RoadBike. To the
MountainBike class, add the private variables tireTread (String) and
mountainRating (int). To the RoadBike class, add the private variable
maximumMPH (int). */
    static class MountainBike extends Bicycle {
        private String tireTread;
        private int mountainRating;
    }
    static class RoadBike extends Bicycle {
        private int maximumMPH;
    }
}

2 个答案:

答案 0 :(得分:3)

您想要整个Bicycle课程的单一计数。制作计数器static

private static int bicycleCount = 0;

如果您需要它是线程安全的,您应该将int更改为AtomicInteger

答案 1 :(得分:0)

使用静态计数器,因为这会将字段标记为类级别而不是实例级别。

对于线程空间使用原子类