-
Notifications
You must be signed in to change notification settings - Fork 2k
Expand file tree
/
Copy pathMissingCallToSuperClone.qhelp
More file actions
50 lines (36 loc) · 1.49 KB
/
MissingCallToSuperClone.qhelp
File metadata and controls
50 lines (36 loc) · 1.49 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
<!DOCTYPE qhelp PUBLIC
"-//Semmle//qhelp//EN"
"qhelp.dtd">
<qhelp>
<overview>
<p>
A <code>clone</code> method that is overridden in a subclass should call <code>super.clone</code>.
Not doing so causes the subclass <code>clone</code> to return an object of the wrong type, which violates
the contract for <code>Cloneable</code>.
</p>
</overview>
<include src="MissingCloneDetails.inc.qhelp" />
<recommendation>
<p>
Every clone method should always use <code>super.clone</code> to construct the cloned object. This ensures that the cloned object
is ultimately constructed by <code>Object.clone</code>, which uses reflection to ensure that an object of the correct
runtime type is created.
</p>
</recommendation>
<example>
<p>In the following example, the attempt to clone <code>WrongEmployee</code> fails because
<code>super.clone</code> is implemented incorrectly in its superclass <code>WrongPerson</code>.</p>
<sample src="MissingCallToSuperCloneBad.java" />
<p>However, in the following modified example, the attempt to clone <code>Employee</code> succeeds
because <code>super.clone</code> is implemented correctly in its superclass <code>Person</code>.</p>
<sample src="MissingCallToSuperCloneGood.java" />
</example>
<references>
<li>
J. Bloch, <em>Effective Java (second edition)</em>, Item 11. Addison-Wesley, 2008.
</li>
<li>
Java API Specification: <a href="https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/Object.html#clone()">Object.clone()</a>.
</li>
</references>
</qhelp>