0

I have to declare an attribute which once initialized can't be modified. It's pretty clear to me that we are talking about a final type, buy my question is whether I can initialize it with the constructor.

Bonus: how should I represent this type of attributes on a UML diagram?

Thanks folks!

Ketterle
  • 15
  • 3
  • 2
    "is whether I can initialize it with the constructor" Did you try it? If you did, you'd find you *have to* initialize it within a constructor if you don't initialize directly on the field. – Andy Turner Apr 23 '21 at 10:02
  • Bonus: https://stackoverflow.com/questions/16252399/how-do-i-add-a-final-variable-to-class-diagram – Andy Turner Apr 23 '21 at 10:02
  • 2
    "It's pretty clear to me that we are talking about a final type" - it sounds more like a final *field* than a final *type*. (Both are valid concepts, but quite different.) – Jon Skeet Apr 23 '21 at 10:04
  • Hey Andy! I didn't try it cos it's just a UML design exercise, not an implementation one. Anyway, your answer put it very clear! Thanks, mate! – Ketterle Apr 23 '21 at 10:51

1 Answers1

2

When you define an attribute as being final it's not that you could, you must either initialize it inline or through the class's constructor. For names of the attributes that represent constants you should use UPPER_CASE_WITH_UNDERSORES and you should represent them in a UML diagram something like this: + MY_CUSTOM_CONSTANT: Integer = 10 (for a public final Integer MY_CUSTOM_CONSTANT = 10;)

Alex Bondor
  • 326
  • 1
  • 9
  • Thanks Alex! Now it's clear to me. Just one more thing: is it mandatory to assign a value on the UML diagram? The thing is we don't know the value until it is passed as a parameter on the constructor. – Ketterle Apr 23 '21 at 10:55
  • oh well.. if the value is not fixed I'm not aware of a method to draw this in a UML diagram.. maybe add a comment there – Alex Bondor Apr 23 '21 at 11:09