在 java 中创建 class 实例的问题

Issue with creating instances of a class in java

我正在尝试制作一个 "Racing Simulator" 来创建和比较车辆。它包括定义车辆的 class 和比较速度的主要 class。当我创建两个 Vehicle 实例并在两个实例上使用我的 getSpeed 方法时,速度是相同的。知道为什么吗?

主要:

public class Main {

    static Vehicle bike, jeep;
    //static Race race;

    public static void main(String args[]) {
        bike = new Vehicle(4000, 20, 30.5, "bike");
        jeep = new Vehicle(3000, 12, 9.8, "Jeep");
        //race = new Race(bike, jeep, 0);
        System.out.println("Bike: " + bike.getTopSpeed() + " Jeep: " + jeep.getTopSpeed());
    }
}

车辆:

public class Vehicle {

    static int _weight, _topSpeed;
    static double _zeroToSixty;
    static String _vehicleName;

    public Vehicle(int weight, int topSpeed, double zeroToSixty, String vehicleName) {
        _weight = weight;
        _topSpeed = topSpeed;
        _zeroToSixty = zeroToSixty;
        _vehicleName = vehicleName;
    }

    public static void setVehicleName(String name) {
        _vehicleName = name;
    }

    public static void setWeight(int weight) {
        _weight = weight;
    }

    public static void setTopSpeed(int topSpeed) {
        _weight = topSpeed;
    }

    public static void setZeroToSixty(double zeroToSixty) {
        _zeroToSixty = zeroToSixty;
    }

    public static String getVehicleName() {
        return _vehicleName;
    }

    public static int getWeight() {
        return _weight;
    }

    public static int getTopSpeed() {
        return _topSpeed;
    }

    public static double getZeroToSixty() {
        return _zeroToSixty;
    }
}

main 的输出是:

"Bike: 12 Jeep: 12"

静态字段在每个类加载器中只存在一次。 将您的静态字段转换为实例字段,您应该没问题。

如果你愿意,你可以在你的 main class 中保持变量静态,但是 Vehicle class 中的所有变量都需要丢失 static 关键字

您尝试过使用

this._topSpeed()

并使用普通变量,而不是静态变量。 为什么要使用下划线?

您将字段声明为 static。这意味着该字段在 class 的所有实例之间 共享 。作为分配给的最后一个值 _topSpeed 是 12(从第二次调用构造函数),这是您在 class.

的两个实例中看到的值

如果您希望每个实例都有自己的 _topSpeed ,您应该删除 static 限定符。这就足够了:

int _weight, _topSpeed;
double _zeroToSixty;
String _vehicleName;

作为最后的评论,将字段声明为 private 通常是个好主意,除非您确实需要它们具有其他类型的访问权限。所以你通常会写:

private int _weight;
private int _topSpeed;
private double _zeroToSixty;
private String _vehicleName;

每个字段单独一行也有助于查看每个字段的完整声明。

每个车辆实例都应该有自己的名称、最高速度、重量等。换句话说,它们应该声明为实例变量,而不是静态的。

更改以下内容:

static int _weight, _topSpeed;
static double _zeroToSixty;
static String _vehicleName;

int _weight, _topSpeed;
double _zeroToSixty;
String _vehicleName;

另外,作为一种好的做法,对这些使用范围限定符 private

对于每个车辆对象应该唯一的特征,您有静态变量。静态使它成为 class 的 属性 而不是对象。制作这些实例变量应该有助于解决您的问题。