简体   繁体   中英

regarding 1st init() and 2nd init()

After deploying the project, when ever the client sends the request for the first time to TestServlet then server creates the testServlet object and then calls first init() method (init(ServletConfig config)). Then JVM checks for the first init() method in TestServlet as it is not available then it checks in super class HttpServlet there also first init method is not available then JVM checks in super class of HttpServlet ie GenericServlet class there first init() is availble then JVM executes it and calls the second init() as the second init() is directly availble in the TestServlet then JVM executes it.

Q.Regarding above para i want to know that how the 1st init() of GenericServlet calls 2nd init() of TestServlet class because in GenericServlet 1st init() internally calls init() which is empty.

That's the basic principle of polymorphism. Since init() is an overridable method, and since the servlet is an instance of TestServlet, which overrides the init() method, the TestServlet implementation of the method is used.

Just like in the following example:

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.
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM