From the Sun docs
Normally, you would put code to initialize an instance variable in a constructor.
There are two alternatives to using a constructor to initialize instance variables: initialize blocks and final methods.
I could understand the use of initialize blocks. Can anyone please explain the use of final methods for instance var initialization? A non-final public setter can do this job. Why not just use them ?
Initializing a final VariableYou can initialize a final variable when it is declared. This approach is the most common. A final variable is called a blank final variable if it is not initialized while declaration.
You can initialize the instance variables of a class using final methods, constructors or, Instance initialization blocks.
You can initialize final instance variables before constructor completes. A blank final instance variable must be definitely assigned at the end of every constructor of the class in which it is declared; otherwise a compile-time error occurs.
Instance variables can be initialized in constructors, where error handling or other logic can be used.
The advantage is already described in the very same Sun tutorial you linked to:
A final method cannot be overridden in a subclass. This is discussed in the lesson on interfaces and inheritance.
This is especially useful if subclasses might want to reuse the initialization method. The method is final because calling non-final methods during instance initialization can cause problems. Joshua Bloch describes this in more detail in Effective Java(item 17 Design and document for inheritance).
The reason a non-final method is dangerous in initialization is because the instance initialization of the superclass executes before the sub class is initialized. Therefore if the non-final method is overriden in the sub class and is executed during the initialization of the superclass it may be accessing uninitialized fields of the subclass giving erroneous results.
The general rule is(quoting from Effective Java): Constructors must not invoke overridable methods, directly or indirectly.
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