According to the tutorial:
The
static
modifier, in combination with thefinal
modifier, is also used to define constants. Thefinal
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?
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With