相信有很多人开始学习Java的时候都和我一样,用的都是《Java核心技术 卷1》,然后对着书敲代码过来的,今天对着书敲就碰到了一个问题,明明和书上一模一样居然也会出错,非常纳闷。下面粘贴我的代码:
package j208180722;
import java.util.Date;
import java.util.GregorianCalendar;
public class EmployeeTest {
public static void main(String[] args) {
Employee[] staff=new Employee[3];
staff[0]=new Employee("Carl Cracker",75000,1987,12,15);
staff[1]=new Employee("Harry Hacker",50000,1989,10,1);
staff[2]=new Employee("Tony Testr",40000,1990,3,15);
for(Employee e:staff){
e.raiseSalary(5);
}
for(Employee e:staff){
System.out.println("name="+e.getName()+",salary="+e.getSalary()+",hireDay="+e.getHireDay());
}
}
class Employee{
private String name;
private double salary;
private Date hireDay;
public Employee(String n,double s,int year,int month,int day){
name=n;
salary=s;
GregorianCalendar calendar=new GregorianCalendar(year,month-1,day);
hireDay=calendar.getTime();
}
public String getName(){
return name;
}
public double getSalary(){
return salary;
}
public Date getHireDay(){
return hireDay;
}
public void raiseSalary(double byPercent){
double raise=salary*byPercent/100;
salary+=raise;
}
}
}
这时编译器报错:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
No enclosing instance of type EmployeeTest is accessible. Must qualify the allocation with an enclosing instance of type EmployeeTest (e.g. x.new A() where x is an instance of EmployeeTest).
at j208180722.EmployeeTest.main(EmployeeTest.java:10)
在网上查询资料以后才知道,在Java里,静态方法不能直接调用动态方法,主程序开头是public static void main,为静态方法,这时候最好的解决方法就是把class 改成static class,将内部类修饰为静态类。最后贴上改正后的代码:
package j208180722;
import java.util.Date;
import java.util.GregorianCalendar;
public class EmployeeTest {
public static void main(String[] args) {
Employee[] staff=new Employee[3];
staff[0]=new Employee("Carl Cracker",75000,1987,12,15);
staff[1]=new Employee("Harry Hacker",50000,1989,10,1);
staff[2]=new Employee("Tony Testr",40000,1990,3,15);
for(Employee e:staff){
e.raiseSalary(5);
}
for(Employee e:staff){
System.out.println("name="+e.getName()+",salary="+e.getSalary()+",hireDay="+e.getHireDay());
}
}
//在Java中,类中的静态方法不能直接调用动态方法,主程序为public static class开头,所以不能直接调用Employee方法
static class Employee{
private String name;
private double salary;
private Date hireDay;
public Employee(String n,double s,int year,int month,int day){
name=n;
salary=s;
GregorianCalendar calendar=new GregorianCalendar(year,month-1,day);
hireDay=calendar.getTime();
}
public String getName(){
return name;
}
public double getSalary(){
return salary;
}
public Date getHireDay(){
return hireDay;
}
public void raiseSalary(double byPercent){
double raise=salary*byPercent/100;
salary+=raise;
}
}
}