gpt4 book ai didi

java - 关于深克隆

转载 作者:行者123 更新时间:2023-11-29 06:44:24 27 4
gpt4 key购买 nike

当我运行下面的代码时,为什么会抛出这个错误?

Exception in thread "main" java.lang.CloneNotSupportedException: Student
at java.lang.Object.clone(Native Method)
at Student.clone(Student.java:44)
at StudentApp.main(StudentApp.java:10)

这是我的主要类(class):

public static void main(String[] args) throws CloneNotSupportedException {

Address address = new Address("湖南省长沙市林科大","1234567",20);
Student stu = new Student("诸葛亮量",20);
stu.setAddress(address);

Student stu2 = (Student)stu.clone();
stu2.setAddress(new Address("湖南省常德市区","484848348",22));

stu2.setName("张飞飞");
stu2.setAge(23);
stu.sayHi();
stu2.sayHi();
}

这是学生类:

public class Student{

private String name;
private int age;
private Address address;

public Address getAddress() {
return address;
}

public void setAddress(Address address) {
this.address = address;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public int getAge() {
return age;
}

public void setAge(int age) {
this.age = age;
}

public Student(String name, int age) {
super();
this.name = name;
this.age = age;
}

public Student() {
super();
}

@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}

public void sayHi() {
System.out.println("大家好,我是" + this.getName() + "同学,我今年" + this.getAge()
+ "岁了……我的HashCode是:" + this.hashCode()+"。我家庭住址是"+address.getAddress()+",家庭住址的HashCode为:"+address.hashCode());
}

}

这是地址类:

public class Address {

private String address;
private String tel;
private int roadNum;

public String getAddress() {
return address;
}

public void setAddress(String address) {
this.address = address;
}

public String getTel() {
return tel;
}

public void setTel(String tel) {
this.tel = tel;
}

public int getRoadNum() {
return roadNum;
}

public void setRoadNum(int roadNum) {
this.roadNum = roadNum;
}

public Address() {
super();
}

public Address(String address, String tel, int roadNum) {
super();
this.address = address;
this.tel = tel;
this.roadNum = roadNum;
}

}

最佳答案

来自javadoc

Invoking Object's clone method on an instance that does not implement the Cloneable interface results in the exception CloneNotSupportedException being thrown.

你试过让你的Student类实现Cloneable接口(interface)吗?

关于java - 关于深克隆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7411395/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com