源代码如下:
package com.bin;public class Test2 { public static void main(String[] args) {
Teacher t = new Teacher(34,"Mis'wang");
Girl g1 = new Girl("Lsiade",18,t);
Girl g2 = (Girl)g1.clone();
g2.t.age = 53;
g2.t.name = "yang";
System.out.println(g1.t.name + " && " + g1.t.age );
}}
class Girl implements Cloneable{
int age ;
String name;
Teacher t ;
public Girl( String name, int age, Teacher t) {
super();
this.age = age;
this.name = name;
this.t = t;
}
public Object clone(){
Girl o = null;
try{
o = (Girl)super.clone();
}catch(CloneNotSupportedException e){
System.err.println(" clone exception");
}
o.t = (Teacher)t.clone();
return o;
}
}class Teacher implements Cloneable{
int age ;
String name;
public Teacher(int age, String name) {
super();
this.age = age;
this.name = name;
}
public Object clone(){
Object o = null;
try{
super.clone();
}catch(CloneNotSupportedException e){
System.err.println(" Clone Not SupportedException ");
}
return o;
}
}Exception in thread "main" java.lang.NullPointerException
为什么
g2.t.age = 53;
g2.t.name = "yang"; 其中 t = null? 请指教.
package com.bin;public class Test2 { public static void main(String[] args) {
Teacher t = new Teacher(34,"Mis'wang");
Girl g1 = new Girl("Lsiade",18,t);
Girl g2 = (Girl)g1.clone();
g2.t.age = 53;
g2.t.name = "yang";
System.out.println(g1.t.name + " && " + g1.t.age );
}}
class Girl implements Cloneable{
int age ;
String name;
Teacher t ;
public Girl( String name, int age, Teacher t) {
super();
this.age = age;
this.name = name;
this.t = t;
}
public Object clone(){
Girl o = null;
try{
o = (Girl)super.clone();
}catch(CloneNotSupportedException e){
System.err.println(" clone exception");
}
o.t = (Teacher)t.clone();
return o;
}
}class Teacher implements Cloneable{
int age ;
String name;
public Teacher(int age, String name) {
super();
this.age = age;
this.name = name;
}
public Object clone(){
Object o = null;
try{
super.clone();
}catch(CloneNotSupportedException e){
System.err.println(" Clone Not SupportedException ");
}
return o;
}
}Exception in thread "main" java.lang.NullPointerException
为什么
g2.t.age = 53;
g2.t.name = "yang"; 其中 t = null? 请指教.
Object o = null;
try{
super.clone();
}catch(CloneNotSupportedException e){
System.err.println(" Clone Not SupportedException ");
}return o;
} 改为
public Object clone(){
Object o = null;
try{
o=super.clone();
}catch(CloneNotSupportedException e){
System.err.println(" Clone Not SupportedException ");
}return o;
} o未赋值就return了