needd
发贴: 55
积分: 0
|
于 2006-03-21 15:39
//main class
public class Animal implements Cloneable{ public Animal(String atype){ type = new String(atype); } public String toString() { return "this is : " +type; } public void sound(){ } private String type; }
//extends animal test clone
public class petDog extends Animal implements Cloneable{ public petDog(String aName,String breed){ super("Dog"); petFlea = new Flea("Max","circus flea"); name = aName; this.breed = breed; } public void setName(String aName){ name = aName; } public Flea getFlea(){ return petFlea; } public Object Clone() throws CloneNotSupportedException{ return super.clone(); //请问这里的super掉用的是 Animal l //里的clone方法吗? 但我Animal没定义 clone方法 } private Flea petFlea; private String name; private String breed; }
public class Flea extends Animal implements Cloneable{ public Flea(String aName,String aSpecies){ super("Flea"); name = aName; species = aSpecies; }
public String toString(){ return super.toString() + "\nIt's" +name + " the "+ species; } public Object Clone() throws CloneNotSupportedException{ return super.clone(); //请问这里的super掉用的是 Animal l //里的clone方法吗? 但我Animal没定义 clone方法 } private String name; private String species; }
public class test2{ public static void main(String[] agrs){ try{ petDog mypet = new petDog("Fang","Chihuahua"); petDog yourpet =(petDog)mypet.Clone(); // yourpet.setName("Gnasher"); // yourpet.getFlea().setName("Atlas"); System.out.println("\nyour pet detail:\n" +yourpet); System.out.println("\nyour pet detail:\n" +mypet); }catch(CloneNotSupportedException e){ e.printStackTrace(System.err); } } }
还有一个问题clone方法为什么要覆盖?书上说: 是否注意到,这里clone()方法修饰符是protected,而不是public。这种访问的不可见性使得我们对Object#clone()方法不可见。。相信读者已明白为什么要覆盖Object#clone()方法。而且,覆盖的方法的修饰符必须是public,如果还保留为protected,覆盖将变得没有实际意义。
但问题是lang package 已经默认引如了,直接访问应该没问题啊? 还有,我去掉了 public 编译器提示说: attemp to assign a weaker access privileges , was protected? 弱的访问权限?? 难道有元 和 prtected有强弱之分吗??? 这里面具体的细节是什么呢?
needd edited on 2006-03-21 23:21
|