import java.util.*;
public class CloneTest {
public static void main (String[] args){ Employee original=new Employee ("wzy",50000);//此处出现错误non-static variable this cannot be referenced from a static context original.setHireDay(2000,1,1);
Employee copy=(Employee)original.clone();
copy.raiseSalary(10);
copy.setHireDay(2002,12,31);
System.out.println("original="+original);
System.out.println("copy="+copy);
}
}//这里加上就不会出现上述错误了,没加的话,它会以为Employee是CloneTest的,就会出现上述错
//误了
class Employee implements Cloneable{
public Employee (String n,double s){
name=n;
salary=s;
}
public Object clone(){
try{
Employee cloned=(Employee)super.clone() ;
cloned.hireDay=(Date)hireDay.clone();
return cloned;
}
catch(CloneNotSupportedException e){return null;} }
public void setHireDay(int year,int month,int day){
hireDay=new GregorianCalendar(year,month -1,day).getTime();
}
public void raiseSalary(double byPercent){
double raise=salary*byPercent/100;
salary+=raise;
}
public String toString(){
return "Employee[name="+name+",salary="+salary+",hireDay="+hireDay+"]";
}
private String name;
private double salary;
private Date hireDay;
}
//删掉这里的},这个程序就没错误了~~~
public class CloneTest {
public static void main (String[] args){ Employee original=new Employee ("wzy",50000);//此处出现错误non-static variable this cannot be referenced from a static context original.setHireDay(2000,1,1);
Employee copy=(Employee)original.clone();
copy.raiseSalary(10);
copy.setHireDay(2002,12,31);
System.out.println("original="+original);
System.out.println("copy="+copy);
}
}//这里加上就不会出现上述错误了,没加的话,它会以为Employee是CloneTest的,就会出现上述错
//误了
class Employee implements Cloneable{
public Employee (String n,double s){
name=n;
salary=s;
}
public Object clone(){
try{
Employee cloned=(Employee)super.clone() ;
cloned.hireDay=(Date)hireDay.clone();
return cloned;
}
catch(CloneNotSupportedException e){return null;} }
public void setHireDay(int year,int month,int day){
hireDay=new GregorianCalendar(year,month -1,day).getTime();
}
public void raiseSalary(double byPercent){
double raise=salary*byPercent/100;
salary+=raise;
}
public String toString(){
return "Employee[name="+name+",salary="+salary+",hireDay="+hireDay+"]";
}
private String name;
private double salary;
private Date hireDay;
}
//删掉这里的},这个程序就没错误了~~~
1. 内隐类的基本用法
1) 如果要在外围class的non-static函数之外产生一个inner class对象,得以OuterClassName.InnerClassName的形式指定该对象的型别。而在non-static函数内则不用。
2) 对于non-static inner class,在外围class的non-static函数可以通过new产生一个inner class对象,但要在非non-static函数产生一个inner class对象,则一定要关联到其enclosing class的某个对象。也就是说,在main方法中不能用new来产生一个Employee对象。