关于clone()方法

Freefish1994 Freefish1994 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
为什么代码里红色部分提示我还要抛异常?
Person类已经重写clone方法也实现Cloneable接口了啊
必须要抛异常才能执行

public class TeatA {

public static void main(String[] args) throws CloneNotSupportedException {
Person p1 = new Person(18,true);
Person p2 = (Person) p1.clone();
System.out.println("p1:" + p1);
System.out.println("p2:" + p2);

}
}

class Person implements Cloneable {
// private String name;
private int age;
private boolean sex;

public Person(int age, boolean sex) {
super();
//this.name = name;
this.age = age;
this.sex = sex;
}

// 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 boolean isSex() {
return sex;
}

public void setSex(boolean sex) {
this.sex = sex;
}

@Override
public String toString() {
return "Person [age=" + age + ", sex=" + sex + "]";
}

@Override
public Object clone() throws CloneNotSupportedException {
// TODO Auto-generated method stub
return super.clone();
}
}
...全文

相关推荐

评论 6
收藏 已收藏
分享
返回顶部
Freefish1994
Java SE 62,620 成员 307,251 内容