Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/eclipse/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java-递增作为类变量的计数器_Java_Constructor - Fatal编程技术网

Java-递增作为类变量的计数器

Java-递增作为类变量的计数器,java,constructor,Java,Constructor,我有一个问题,其中一部分说: 类别车辆有4个属性,即noOfTyres、accessories、brand和counter,分别为整数、布尔、字符串和整数类型。计数器是一个类变量。类的构造函数初始化所有3个变量,并将计数器递增1 对于这一部分,我想到了两种方法,但我不确定哪一种是正确的,或者两者是否都正确 第一个是: public class Vehicle{ private int noOfTyres; private Boolean accesories; private Str

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

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

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

第一个是:

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;}

}
第二个是:

  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;
 }

}

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

要使某个对象成为类变量而不是实例变量,我们需要使其成为静态的

更多关于
静态
变量及其与常规变量的区别:

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

谢谢!这很有帮助:D@Diksha没问题,很乐意帮忙!如果这对你有用的话,如果你接受它作为回答,我将不胜感激。当然!你活该!