0

What happens when I declare something like:

public static final String forma = "Rectangular";

Isn't it redundant? Being String a final class, what would it change not setting forma as final? For static, I think it is not making any change.

diegoaguilar
  • 8,179
  • 14
  • 80
  • 129

5 Answers5

3

final make sure reference is not assigned to new value.

If you don't make it final, it is valid to assign some other value to forma (or) you can do some operation on Rectangular and assign results back to forma

kosa
  • 65,990
  • 13
  • 130
  • 167
1

For object-types 'final' modifier means that REFERENCE to this object cannot be changed, not it's value!

kovrik
  • 159
  • 1
  • 4
1

See String is a final class,and final keyword makes references final not object final.
Final object means it can't be altered but final reference means it can't be assigned to another object after first assignment.

Being final means you can not modify the object String s="hello", "hello" is the string object and it cant be modified, but about s if its a non-final reference and i do thing like:s=s.concat("bing") then, "hello" is taken can concatenated with "bing" object and then assigned to s means "hello" and "bing" objects are not modified they lost their references and non-final reference s is now referring to a new object "hellobing".
I surely wanna help you more if you find this interesting.

Sachin Verma
  • 3,712
  • 10
  • 41
  • 74
0

Isn't it redundant?

No, it is not redundant. It is constant. Every keyword of this statement has meaning. final make it immutable, static make it class variable and public make it globally accessible.

Masudul
  • 21,823
  • 5
  • 43
  • 58
0

The final keyword is heavily overloaded, and means very different things in different contexts:

  • On fields and local variables, it indicates that the content of a reference cannot be changed. (This is different from immutability.)
  • On classes, it indicates that the class cannot be subclassed.
  • On methods, it indicates that the method cannot be overridden in subclasses.
Louis Wasserman
  • 191,574
  • 25
  • 345
  • 413