如何使一个变量在所有创建的相同类型的对象中保持相同?

huangapple go评论62阅读模式
英文:

How can I set a variable to be the same across all created objects of the same type?

问题

假设我有一个叫做 Car 的类。在这个类中有一些方法和其他变量。我有一个名为 make 的变量,然而需要保证所有的 Car 对象中这个变量的值都是相同的。唯一的问题是,在初始化 Car 对象之前,我想知道 make 的值是什么。我尝试过使用静态方法,但我可能对静态方法和静态变量的工作原理有误解。我尝试调用一个设置静态变量的静态方法,但当我创建一个 Car 对象时,它没有起作用。

例如:Car.setMake("Toyota")

其中静态方法 setMake() 设置了静态变量 make
然后我会创建一个 new Car(),并期望所有的 Car 对象的 make 都是 "Toyota"。但这并不起作用。

英文:

Let's say I have a class I made called Car. In that class there is methods and other variables. I have a variable called make though that needs to always be the same across all Car objects. The only problem is I want to know what make will be before a Car object has been initialized. I tried using static but I must have a misconception of how static methods and static variables function. I tried calling a static method which sets the static variable but when I create a Car object it did not work.

example: Car.setMake("Toyota")

Where the static method setMake() sets the static variable make.
Then I would create a new Car() and expect all Car objects to be of the make "Toyota". This does not work.

答案1

得分: 4

你对于 static 变量的理解是正确的。再次检查一下。Static 变量和方法属于该 Class 本身,Class 的所有实例都具有相同的值。
Static 方法只能访问 static 变量和方法,但是 non-static 方法可以访问 staticnon-static 变量以及方法。

public static void main(String... args) {
    Car audi = new Car();
    Car bmw = new Car();
    System.out.println(Car.getMake());  // null
    Car.setMake("Toyota");
    System.out.println(Car.getMake());  // Toyota
    System.out.println(audi.getMake()); // Toyota
    System.out.println(bmw.getMake());  // Toyota
}

class Car {

    private static String make;

    public static void setMake(String make) {
        Car.make = make;
    }

    public static String getMake() {
        return make;
    }

}
英文:

You're right about static variables. Check it again. Static variables and mothods bolong to the Class itselfe and all instances of Class have the same values.
Static methods have access to static variables and methods only, but non-static methods have access to static and non-static variables and methods.

public static void main(String... args) {
    Car audi = new Car();
    Car bmw = new Car();
    System.out.println(Car.getMake());  // null
    Car.setMake("Toyota");
    System.out.println(Car.getMake());  // Toyota
    System.out.println(audi.getMake()); // Toyota
    System.out.println(bmw.getMake());  // Toyota
}

class Car {

    private static String make;

    public static void setMake(String make) {
        Car.make = make;
    }

    public static String getMake() {
        return make;
    }

}

huangapple
  • 本文由 发表于 2020年9月21日 03:37:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/63982938.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定