问题描述
- Object的clone()方法为什么要存在?这个方法不是更简单吗?请指教,谢谢!
-
当我看到Object的clone方法时产生了一个问题:
为什么要用clone方法呢?我完全可以在该类中定义一个方法,在在该方法返回中返回一个该类本身的实例即可。就像下面这个例子:package excercise.inheritance;
public class Override {
public static void main(String[] args) { Chicken chicken=new Chicken("vivid","red"); System.out.println(chicken.getName()+" "+chicken.getCrest()); Chicken chickenCP=chicken.getCopied();
//这和clone有什么区别吗?
chickenCP.setCrest("blue");
chickenCP.setName("leo");
System.out.println(chickenCP.getName()+" "+chickenCP.getCrest());System.out.println(chicken.getName()+" "+chicken.getCrest()); }
}
class Bird{
protected String name;public String getName() { return name; } public void setName(String name) { this.name = name; } public Bird(String name){ this.name=name; } public Bird getCopied(){ return new Bird(name);
//不必要用clone呀,我可以直接返回一个实例不就行了吗?
}
}
class Chicken extends Bird{
protected String crest; public String getCrest() { return crest; } public void setCrest(String crest) { this.crest = crest; } public Chicken(String name,String crest) { super(name); // TODO Auto-generated constructor stub this.crest=crest; } public Chicken getCopied(){//返回的类为基类的返回类的派生类 return new Chicken(name,crest); }
}
时间: 2024-12-11 17:36:21