org.sonar.l10n.java.rules.squid.S2157.html Maven / Gradle / Ivy
The newest version!
Simply implementing Cloneable
without also overriding Object.clone()
does not necessarily make the class cloneable. While the Cloneable
interface does not include a clone
method, it is required by convention, and ensures true cloneability. Otherwise the default JVM clone
will be used, which copies primitive values and object references from the source to the target. I.e. without overriding clone
, any cloned instances will potentially share members with the source instance.
Removing the Cloneable
implementation and providing a good copy constructor is another viable (some say preferable) way of allowing a class to be copied.
Noncompliant Code Example
class Team implements Cloneable { // Noncompliant
private Person coach;
private List<Person> players;
public void addPlayer(Person p) {...}
public Person getCoach() {...}
}
Compliant Solution
class Team implements Cloneable {
private Person coach;
private List<Person> players;
public void addPlayer(Person p) { ... }
public Person getCoach() { ... }
@Override
public Object clone() {
Team clone = (Team) super.clone();
//...
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy