I can't solve this... I keep getting " tree.clone can't be overridden"
Pls help
Under discussion
Comments (3)
- Popular
- New
- Old
You must be signed in to leave a comment
Ibrahim
17 January, 09:57
Compare your solution to mine:
public class Solution {
public static void main(String[] args) {
Tree tree = new Tree("willow", new String[]{"s1", "s2", "s3", "s4"});
Tree clone = null;
try {
clone = (Tree) tree.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
System.out.println(tree);
System.out.println(clone);
System.out.println(tree.branches);
System.out.println(clone.branches);
}
public static class Plant{
private String name;
public Plant(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
public static class Tree extends Plant implements Cloneable {
private String[] branches;
public Tree(String name, String[] branches) {
super(name);
this.branches = branches;
}
public String[] getBranches() {
return branches;
}
@Override
protected Object clone() throws CloneNotSupportedException {
Tree tree = (Tree) super.clone();
tree.branches = branches.clone();
return tree;
}
}
}
0
Banak
13 February 2021, 16:04
You cannot cloned plant ...look at your Object.equals method..???
0
Nouser
10 September 2020, 08:50
Plant is not cloneable, so line 64 won't work. However you could create a new Tree object (inside the clone method) and then clone the branches.
0