Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do final (constant) instance (non-static) variables act like class (static) variables?

In the following example, the variable b is declared final, but not static. That means it's a constant instance variable. However, because it's constant, none of the Passenger objects can change its value. So isn't it better to declare it static and make it a class variable, so that there is only one copy to be used by all instantiated objects?

class Passenger {
    int a;
    final int b = 0;

    void drive() {
        System.out.println("I'm driving!");
    }
}
like image 765
Nitin Garg Avatar asked Feb 20 '26 22:02

Nitin Garg


2 Answers

The purpose of final but non-static variables is to have an object-wide constant. It should be initialized in the constructor:

class Passenger {
    final int b;

    Passenger(int b) {
        this.b = b;
    }
}

If you are always assigning a constant literal value (0) to the final variable, it doesn't make much sense. Using static is preferred so that you are only having a single copy of b:

static final int b = 0;

BTW I don't think having default access modifier was your intention.

like image 85
Tomasz Nurkiewicz Avatar answered Feb 22 '26 10:02

Tomasz Nurkiewicz


It depends on the purpose of b. Usually constants are there for a specific purpose. If you make it static you could accidentally change it in some instance of that class and that will affect all the others.

like image 39
Bogdan Emil Mariesan Avatar answered Feb 22 '26 12:02

Bogdan Emil Mariesan