Java-增加一个类变量的计数器

Tia*_*Tia 4 java constructor

我有一个问题,其中一部分说:

Vehicle 类有 4 个属性,即 noOfTyres、accessories、brand 和 counter,其类型分别为整数、布尔、字符串和整数。Counter 是一个类变量。该类的构造函数初始化所有 3 个变量并将计数器加一。

我为这部分想到了两种方法,但我不确定哪一种是正确的,或者两者是否都是正确的。

第一个是:

public class Vehicle{
  private int noOfTyres;
  private Boolean accesories;
  private String brand;
  private int static counter=0;
  private int counterNum;

public Vehicle(int noOfTyres, int accessories, int brand){
 counter++;
 this.noOfTyres= noOfTyres;
 this.accessories= accessories;
 this.brand= brand;
 counterNum= counter;}

}
Run Code Online (Sandbox Code Playgroud)

第二个是:

  public class Vehicle{
   private int noOfTyres;
   private Boolean accesories;
   private String brand;
   private int counter=0;


public Vehicle(int noOfTyres, int accessories, int brand){
 counter++;
 this.counter= counter;
 this.noOfTyres= noOfTyres;
 this.accessories= accessories;
 this.brand= brand;
 }

}
Run Code Online (Sandbox Code Playgroud)

根据问题提供的信息类型/数量,哪种方法(如果其中任何一个是好的)是合适的?

nho*_*er9 5

为了使某个东西成为类变量而不是实例变量,我们需要将其设为static

有关static变量以及它们与常规变量有何不同的更多信息:https://en.wikipedia.org/wiki/Static_variable

TLDR:你的第一个解决方案是正确的,尽管我认为它应该读 private static int counter = 0;