java-克隆对象
上代码
输出结果
下面是源代码
public class Demo21401 {//205方法的妙用
public static void main(String[] args) {
//1编写MyTools类,编写方法可以打二维数组的数据
int [][]map = {{0,1,2},{3,4,5},{6,7,8}};
MyTools tool = new MyTools();
tool.printArr(map);
Person p = new Person();
p.name = "milan";
p.age = 100;
MyTools tools = new MyTools();
Person p2 = tools.copyPerson(p);
//到此 p和p2都是两个独立的对象 属行相同
System.out.println("p的属性 age="+p.age+"名字="+p.name);
System.out.println("p2的属性 age="+p2.age+"名字="+p2.name);
//比较两个是否是同一个对象
System.out.println(p==p2);//false
}
}
class Person{
String name;
int age;
}
class MyTools{
public Person copyPerson(Person p){
Person p2 = new Person();
p2.name = p.name;
p2.age = p.age;
return p2;
}
public void printArr(int[][] map){
for (int i = 0; i < map.length; i++) {
for (int j =0; j < map[i].length;j++) {
System.out.print(map[i][j]+"\t");
}
System.out.println();
}
}
}