Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

On the static final keywords in Java

According to the tutorial:

The static modifier, in combination with the final modifier, is also used to define constants. The final modifier indicates that the value of this field cannot change.

I would agree with this only if the types involved were primitive. With reference types, e.g. an instance of a class Point2D where its position attributes were not final (i.e., we could change its position), the attributes of this kind of variables such as public static final Point2D A = new Point2D(x,y); could still be changed. Is this true?

like image 200
Pippo Avatar asked Jan 16 '13 12:01

Pippo


People also ask

Can we write static and final keyword with method?

The final keyword can be applied with the variables, a final variable that have no value it is called blank final variable or uninitialized final variable. It can be initialized in the constructor only. The blank final variable can be static also which will be initialized in the static block only.

What's the difference between final and static?

The main difference between static and final is that the static is used to define the class member that can be used independently of any object of the class. In contrast, final is used to declare a constant variable or a method that cannot be overridden or a class that cannot be inherited.


2 Answers

Yes, it can be changed. Only the references cannot be changed, but its internal fields can be. The following code shows it:

public class Final {     static final Point p = new Point();     public static void main(String[] args) {         p = new Point(); // Fails         p.b = 10; // OK         p.a = 20; // Fails     } }  class Point {     static final int a = 10;     static int b = 20; } 

Groovy (an alternative JVM language) has an annotation called @Immutable, which blocks changing to a internal state of an object after it is constructed.

like image 183
Will Avatar answered Sep 19 '22 19:09

Will


Correct, it can still be changed. The "static final", in this case, refers to the reference itself, which cannot be changed. However, if the object that it is references is mutable, then the object that it references can be changed.

An immutable object, such as a String, will be a constant.

like image 30
Jaco Van Niekerk Avatar answered Sep 21 '22 19:09

Jaco Van Niekerk