Ruba Ruba - 1 month ago 6
Java Question

final and static in Java

I have read this sentence in a book but I didn't understand it:

A field that is both static and final has only one piece of storage that cannot be changed.

Can anyone explain it for me?


The source of your confusion may be that the word "static" in english and it's meaning in Java are only loosely related.

A variable defined in a class Cat in the "normal" way can be referred to as an instance variable.

class Cat {
   int weight;

Each time you create a new object of type Cat, you create a new copy of the variable 'weight'. If you create 10 objects of type Cat, each one has it's own copy of the weight variable.

A 'static' variable can be thought of as a class level variable, as opposed to an instance variable. A static variable has only one copy and belongs to the class Cat itself, rather than there being one copy for each object of type Cat.

class Cat {
   static String speciesName;

   int weight;

Here, no matter how many objects of type Cat we create, there is only one copy of speciesName.

If the static variable is also 'final,' than this one copy of the variable is the only piece of storage that cannot be changed. If the variable 'weight' were final in the above example, there would be 10 pieces of storage which could not be changed -- one for each object of type Cat that we had created.