Пробол копировать
Arrays.copyOf() this.branches.clone()
Сейчас перебрал в цикле массив.
И все равно пишет что объект должен быть новый.
Так вроде он вообще новый!!!package com.javarush.task.task21.task2108;
import java.util.Arrays;
/*
Клонирование растений
*/
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 abstract class Plant{
private String name;
public Plant(String name) {
this.name = name;
}
public String getName() {
return name;
}
public abstract Tree Clone() throws CloneNotSupportedException;
}
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
public Tree Clone() throws CloneNotSupportedException {
String[]stclo = new String[this.branches.clone().length];
for (int i = 0; i <stclo.length ; i++) {
stclo[i]=this.branches[i];
}
return new Tree("Новый объект",stclo);
}
}
}