Java final modifier

I was told that, I misunderstand effects of final. What are the effects of final keyword?

Here is short overview of what I think, I know:

Java final modifier (aka aggregation relation)

primitive variables: can be set only once. (memory and performance gain)
objects variables: may be modified, final applies to object reference.
fields: can be set only once.
methods: can't be overridden, hidden.
classes: can't be extended.
garbage collection: will force Java generational garbage collection mark-sweep to double sweep.

Can's and Cant's

  • Can make clone fail (this is both good and bad)
  • Can make immutable primitives aka const
  • Can make blank immutable - initialized at creation aka readonly
  • Can make objects shallowly immutable
  • Can make scope / visibility immutable
  • Can make method invocation overhead smaller (because it does not need virtual table)
  • Can make method arguments used as final (even if thy are not)
  • Can make objects threadsafe (if object is defined as final, it wont make method arguments final)
  • Can make mock tests (not that you could do anything about it - you can say bugs are intended)
  • Can't make friends (mutable with other friends and immutable for rest)
  • Can't make mutable that is changed to be immutable later (but can with factory pattern like fix)
  • Can't make array elements immutable aka deeply immutable
  • Can't make new instances of object (this is both good and bad)
  • Can't make serialization work

There are no alternatives to final, but there is wrapper + private and enums.

54
задан Margus 28 October 2010 в 12:39
поделиться