Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using final methods to initialize an instance variable

Tags:

java

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 ?

like image 500
gameover Avatar asked Jan 28 '10 12:01

gameover


People also ask

Can we initialize final variable in method?

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.

Which method is used to initialize the instance variable of a class?

You can initialize the instance variables of a class using final methods, constructors or, Instance initialization blocks.

When can final instance variables be initialized?

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.

Where can a final instance variable be initialized?

Instance variables can be initialized in constructors, where error handling or other logic can be used.


1 Answers

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.

like image 174
BalusC Avatar answered Oct 28 '22 12:10

BalusC