— > 类和类本身具有共同特征,将这些特征提取出来,形成的就叫做抽象类。抽象类本身并不存在,所以无法创建对象。
–>不往抽象了说,最直观的就是实现接口中的方法,供子类继承和重写。
我们拿“Servlet”接口进行举例
OneServlet实现类
1.问题:为什么OneServlet不直接实现Servlet接口,而要继承HttpServlet抽象类?
-----》 继承HttpServlet接口可以有选择的重写我们需要的方法,降低程序的开发难度。
public class OneServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("OneServlet类针对浏览器发送GET请求方式处理");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("OneServlet类针对浏览器发送POST请求方式处理");
}
}
Servlet接口
public interface Servlet {
void init(ServletConfig var1) throws ServletException;
ServletConfig getServletConfig();
void service(ServletRequest var1, ServletResponse var2) throws ServletException, IOException;
String getServletInfo();
void destroy();
}
抽象类GenericServlet 对应实现接口Servlet
public abstract class GenericServlet implements Servlet, ServletConfig, Serializable {
public void destroy() {}
public void init(ServletConfig config) throws ServletException {
this.config = config;
this.init();
}
public abstract void service(ServletRequest var1, ServletResponse var2) throws ServletException, IOException;
public String getServletInfo() {
return "";
}
public ServletConfig getServletConfig() {
return this.config;
}
}
抽象类HttpServlet父类对应抽象类GenericServlet
public abstract class HttpServlet extends GenericServlet {
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String protocol = req.getProtocol();
String msg = lStrings.getString("http.method_get_not_supported");
if (protocol.endsWith("1.1")) {
resp.sendError(405, msg);
} else {
resp.sendError(400, msg);
}
}
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String protocol = req.getProtocol();
String msg = lStrings.getString("http.method_post_not_supported");
if (protocol.endsWith("1.1")) {
resp.sendError(405, msg);
} else {
resp.sendError(400, msg);
}
}
}