谁能在 java servlet 中向我解释这段代码?这是动态多态性(覆盖)吗?如果是这样,这怎么可能?

Can anyone explain me this code in java servlets ? is this dynamic polymorphism (overridding)? if so how is this possible?

HttpSession session = request.getSession(); 这里 HttpSession 是一个接口,request 是扩展 ServletRequest 的接口 HttpServletRequest 的对象。这个实例化是如何通过调用另一个接口的方法来完成的呢?我知道这是一个基本问题,但我是 Java 的新手。所以,谁能给我解释一下?

#getSession()是一个方法,return类型为HttpSession。这里没有实例化,它只是 returns session 属性 of the HttpServletRequest.

更详细一点:HttpServletRequest是一个接口,它指定它的每个实现都应该有#getSession()方法。实际的 HttpServletRequest 实现(由 servlet 容器提供)实现(覆盖)此方法,这就是 HttpSession 对象的来源。

比如Tomcat自己实现的接口是org.apache.catalina.core.ApplicationHttpRequest,源码是here.

request 对象的 getSession() 方法 returns class 的对象实现了 HttpSession 接口。您没有直接进行实例化。这里的要点是 getSession() 方法以某种方式可以访问实现 HttpSession 的对象,但是从您展示的代码中您不知道它的确切来源。为此,您必须查看 class 实现。