【问题标题】:regarding 1st init() and 2nd init()关于第一个 init() 和第二个 init()
【发布时间】:2012-12-16 15:25:10
【问题描述】:

部署项目后,当客户端第一次向 TestServlet 发送请求时,服务器会创建 testServlet 对象,然后调用第一个 init() 方法(init(ServletConfig config))。然后JVM检查TestServlet中的第一个init()方法,因为它不可用然后它检查超类HttpServlet也有第一个init方法不可用然后JVM检查HttpServlet的超类,即GenericServlet类第一个init()可用然后 JVM 执行它并调用第二个 init(),因为第二个 init() 直接在 TestServlet 中可用,然后 JVM 执行它。

Q.关于上面的段落,我想知道 GenericServlet 的第一个 init() 是如何调用 TestServlet 类的第二个 init() 的,因为在 GenericServlet 中,第一个 init() 内部调用的是空的 init()。

【问题讨论】:

    标签: java jakarta-ee servlets


    【解决方案1】:

    这就是多态的基本原理。由于init() 是一个可重写的方法,并且由于servlet 是TestServlet 的一个实例,它重写了init() 方法,所以使用该方法的TestServlet 实现。

    就像下面的例子:

    public class Animal {
        public void saySomething() {
            // do nothing
        }
    
        public void saySomethingElse() {
            saySomething();
        }
    }
    
    public class Dog extends Animal {
        @Override
        public void saySomething() {
            System.out.println("bark!");
        }
    }
    
    public class Main {
        public static void main(String[] args) {
            Animal animal = new Dog();
            animal.saySomething(); // bark!, because the animal is a dog
    
            animal.saySomethingElse(); // still bark!, because the animal is a dog
                                       // and saySomethingElse() calls the animal's
                                       // polymorphic saySomething() method.
        }
    }
    

    【讨论】:

    • 非常感谢 :-) 解释得很好。
    猜你喜欢
    • 2018-01-16
    • 2015-10-20
    • 2018-05-17
    • 2021-04-23
    • 2017-07-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多