4

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?

1 Answer 1

5

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;

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.