Object
无有参构造
public Object() 空参构造
成员方法:
public String toString() 返回对象的字符串表示
public boolean equals(object obj) 比较两个对象是否相等
Object默认用==号比较地址值,需要重写才能比较属性值
protected Object clone(int a) 对象克隆
对象克隆
把a对象的属性值完全拷贝给b对象,也叫对象拷贝,对象复制
深克隆:基本数据类型拷贝过来,字符串复用,引用数据类型会重新创建新的
浅克隆:不管对象内部的属性是基本数据类型还是引用数据类型,都完全拷贝下来
object中的是浅克隆
深克隆需要重写
浅克隆
import java.util.Arrays;public class student implements Cloneable{private int age;private String name;private int[] date;public student() {}public student(int age, String name, int[] date) {this.age = age;this.name = name;this.date = date;}/*** 获取* @return age*/public int getAge() {return age;}/*** 设置* @param age*/public void setAge(int age) {this.age = age;}/*** 获取* @return name*/public String getName() {return name;}/*** 设置* @param name*/public void setName(String name) {this.name = name;}/*** 获取* @return date*/public int[] getDate() {return date;}/*** 设置* @param date*/public void setDate(int[] date) {this.date = date;}public String toString() {return "student{age = " + age + ", name = " + name + ", date = " + Arrays.toString(date) + "}";}//调用父类的clone,相当于Java帮我们克隆@Overrideprotected Object clone() throws CloneNotSupportedException {return super.clone();}
}
public class Main {public static void main(String[] args) throws CloneNotSupportedException{int[]date={1,2,3,4,5,6,7};student a=new student(15,"hangman",date);//浅克隆student b=(student)a.clone();System.out.println(a);System.out.println(b);}
}
深克隆
import java.util.Arrays;public class student implements Cloneable{private int age;private String name;private int[] date;public student() {}public student(int age, String name, int[] date) {this.age = age;this.name = name;this.date = date;}/*** 获取* @return age*/public int getAge() {return age;}/*** 设置* @param age*/public void setAge(int age) {this.age = age;}/*** 获取* @return name*/public String getName() {return name;}/*** 设置* @param name*/public void setName(String name) {this.name = name;}/*** 获取* @return date*/public int[] getDate() {return date;}/*** 设置* @param date*/public void setDate(int[] date) {this.date = date;}public String toString() {return "student{age = " + age + ", name = " + name + ", date = " + Arrays.toString(date) + "}";}//调用父类的clone,相当于Java帮我们克隆@Overrideprotected Object clone() throws CloneNotSupportedException {int[]date=this.date;int[]newdate=new int[date.length];for (int i = 0; i < date.length ; i++) {newdate[i]=date[i];}//调用父类克隆方法student a=(student)super.clone();a.date=newdate;return a;}
}
public class Main {public static void main(String[] args) throws CloneNotSupportedException{int[]date={1,2,3,4,5,6,7};student a=new student(15,"hangman",date);//深克隆student b=(student)a.clone();int[]arr= a.getDate();arr[0]=100;System.out.println(a);System.out.println(b);}
}