日期:2014-05-19  浏览次数:20781 次

struts中调用接口时候的Cannot make a static reference to the non-static method问题
用struts想实现一个注册的功能,注册成功就跳转到success的页面,失败就跳回到注册页面
写了一段DAO:
public interface AddStudentDAO {

public boolean addStudent(AddStudentForm studentForm);

}


实现DAO的方法:
public class Student implements AddStudentDAO {

@Override
public boolean addStudent(AddStudentForm studentForm) {

return false;
}

}


action的代码:
public class AddStudentAction extends Action {

@Override
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {

//转型
AddStudentForm addStudentForm=(AddStudentForm)form;

//调用接口
AddStudentDAO student=new AddStudentDAO();
  boolean successful=false;
successful=AddStudentDAO.addStudent(addStudentForm);
//关键字
String returnURLKeyWord = "addFailure";
if(successful == true){
returnURLKeyWord = "addSuccess";
}

return mapping.findForward(returnURLKeyWord);
}



}


红色部分报错,我是按教学视频中来的,视频中DAO这个接口实例化了。。。
如果我把
//调用接口
AddStudentDAO student=new AddStudentDAO();
boolean successful=false;
successful=AddStudentDAO.addStudent(addStudentForm);
改成
  Student student=new Student();
boolean successful=false;
successful=AddStudentDAO.addStudent(addStudentForm);

最后的那行successful=AddStudentDAO.addStudent(addStudentForm)还是报错,
Cannot make a static reference to the non-static method


如果在Student类中把addStudent方法变成static的,那又会提示
Illegal modifier for the interface method addStudent; only public & abstract are permitted


大家指点指点

------解决方案--------------------
AddStudentDAO student=new AddStudentDAO(); 
boolean successful=false;
successful=AddStudentDAO.addStudent(addStudentForm);
 
红色部分改成 student
------解决方案--------------------
AddStudentDAO.addStudent()这只能调用静态static方法,因为调用主体是AddStudentDAO这个类而不是一个类的实例对象。
而addStudent()不是静态方法,所以报错。
改用student.addStudent()方法就好了,因为student是这个类的一个实例对象