不明白为什么实现克隆的时候出现
NullPointerException问题
今天学习克隆的时候出现了一个NullPointerException的问题
下面是代码
public class StringTest {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Professor p=new Professor("Wangwu",50);
Student s1=new Student("zhangsan",21,p);
Student s2=(Student)s1.clone();
s2.p.name="lisi";
System.out.println(s1.p.name);
}
}
class Professor
{
String name;
int age;
Professor(String name,int age)
{
this.name=name;
this.age=age;
}
}
class Student implements Cloneable
{
String name;
int age;
Professor p;
Student(String name, int age, Professor p)
{
this.name=name;
this.age=age;
}
public Object clone()
{
Object o=null;
try
{
o=(Student)super.clone();
}
catch(CloneNotSupportedException cse)
{
System.out.println(cse.getMessage());
}
return o;
}
}
错误信息:
Exception in thread "main"
java.lang.NullPointerException at StringTest.main(StringTest.java:14)
如果红色字体换成
System.out.println(s1.name);
就不会出错
不知道是为什么
------解决方案--------------------LZ如果是要做clone()方法的验证的话,s2.p.name="lisi";
System.out.println(s1.p.name);
这个好象是多余的.
直接打印:
System.out.println(s2.name);
不就可以验证了!
------解决方案--------------------Java code
Student(String name, int age, Professor p)
{
this.name=name;
this.age=age;
this.p = p;//这里要给成员变量初始化!
}
------解决方案--------------------