-
Notifications
You must be signed in to change notification settings - Fork 2k
Expand file tree
/
Copy pathNoNonFinalInConstructor.qhelp
More file actions
57 lines (43 loc) · 1.58 KB
/
NoNonFinalInConstructor.qhelp
File metadata and controls
57 lines (43 loc) · 1.58 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
<!DOCTYPE qhelp PUBLIC
"-//Semmle//qhelp//EN"
"qhelp.dtd">
<qhelp>
<overview>
<p>If a constructor calls a method that is overridden in a subclass,
it can cause the overriding method in the subclass
to be called before the subclass has been initialized. This can lead to unexpected results.
</p>
</overview>
<recommendation>
<p>Do not call a non-final method from within a constructor if that method
could be overridden in a subclass.</p>
</recommendation>
<example>
<p>
In the following example, executing <code>new Sub("test")</code> results in a <code>NullPointerException</code>.
This is because the subclass constructor implicitly calls the superclass constructor, which in turn
calls the overridden <code>init</code> method before the field <code>s</code> is initialized in the subclass constructor.
</p>
<sample src="NoNonFinalInConstructor.java" />
<p>
To avoid this problem:
</p>
<ul>
<li>The <code>init</code> method in the super constructor should be made <code>final</code> or <code>private</code>.</li>
<li>The initialization that is performed in the overridden <code>init</code> method in the subclass
can be moved to the subclass constructor itself, or delegated to a separate final
or private method that is called from within the subclass constructor.</li>
</ul>
</example>
<references>
<li>
J. Bloch,
<em>Effective Java (second edition)</em>, pp. 89–90.
Addison-Wesley, 2008.
</li>
<li>
The Java Tutorials:
<a href="https://docs.oracle.com/javase/tutorial/java/IandI/final.html">Writing Final Classes and Methods</a>.
</li>
</references>
</qhelp>