简体   繁体   中英

Java- incrementing a counter which is a class variable

I have a question where part of it says:

The class Vehicle has 4 attributes namely noOfTyres, accessories, brand and counter which are of type integer, Boolean, String and integer respectively. Counter is a class variable. The constructor of the class initialises all 3 variables and increments the counter by one.

I have thought of two approaches for this part and I am not sure which one is correct or if both of them is.

The first one is:

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

}

The second one is:

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

}

Which approach(if any of them is good) is suitable based on the type/amount of info the question gave?

To make something a class variable rather than an instance variable, we need to make it static .

More on static variables and how they are different from regular ones here: https://en.wikipedia.org/wiki/Static_variable

TLDR: your first solution is right, allthough I think it should read private static int counter = 0;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM