Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 961
Tia Avatar asked Sep 15 '25 16:09

Tia


1 Answers

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;

like image 86
nhouser9 Avatar answered Sep 17 '25 07:09

nhouser9