Home > other >  how to increment final attribute variable in constructor?
how to increment final attribute variable in constructor?

Time:12-13

In my homework, I have a Java class with attributes

private final int idOfPassenger;
private final String name;

in the constructor which takes only a String as parameter, I am supposed to initialise both the name and the id of the passenger. But every time I create a new Passenger, I am supposed to increment the idOfPassenger variable by one (starting from 0), so no passengers have the same number.

I am not allowed to change the private final or the constructor parameters. How do I increment idOfPassengers by 1 every time I create a new passenger?

public class Passenger {

    private final int idOfPassenger;
    private final String name;

    public Passenger(String name) {
        this.name = name;
        this.idOfPassenger = 0;
    }
}

CodePudding user response:

The point of a final field is that it cannot be reassigned to a new value. So you cannot increment it. But you misunderstand the assignment. You are not supposed to increment private final int idOfPassenger; of your existing objects but instead always initialize it with one value higher than the last created object when creating a new object. You can realize that behavior by introducing a static field that belongs to the class and not any specific object:

public class Passenger {

    private final int idOfPassenger;
    private final String name;
    private static int currentId = 0;

    public Passenger(String name) {
        currentId  ;
        this.name = name;
        this.idOfPassenger = currentId;
    }
}

This will create a static field that belong to the class and all your objects share. It is initialized with 0, then each time a new object gets created that static field is incremented and the final int idOfPassenger value set to the current value of that static field.

  • Related