Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are non-static final variables useful in Java?

Tags:

java

This question discusses the practices of non-static final variables.

My first impression is that non-static final variables are useless because final variables cannot be reassigned after initialization.

class Foo {
    public static final int BAR = 10;
}

That would mean all the objects created from type Foo would have BAR = 10.

When would it be useful, practical, or accepted to use non static, but final variables, like so?

class Foo {
    public final int BAR = 10;
}

So in what case does the latter become useful? Since it basically means the same thing.

like image 217
EDToaster Avatar asked Dec 15 '22 20:12

EDToaster


1 Answers

When that same animal has a field like this:

private final Animal mother;

Everyone only has one biological mother and there is no shared mom, meaning it is specific for each instance.

Making it static means that the value is shared amongst all instances. If this is what you want then it makes sense ofcourse.

like image 193
Jeroen Vannevel Avatar answered Dec 17 '22 09:12

Jeroen Vannevel