user460920
user460920

Reputation: 887

why to use public modifier in servlet

I want some info to prepare the first servlet program.

Can anyone let me know that why we declare the userdefined class as public in servlet as well as init(), service() and destroy() also as public.

Can we use other access modifiers then which are they? Why to use only public modifiers?

Upvotes: 1

Views: 1608

Answers (2)

Ravindra Gullapalli
Ravindra Gullapalli

Reputation: 9178

We have to declare servlet class and the methods init, service and destroy as public because the server should be able to access these. This is very similar to the main method declaring with the access modifier public.

Another reason is in HttpServlet and in GenericServlet classes, these three methods are public whose access level you can not reduce in inherited classes.

Upvotes: 2

Bozho
Bozho

Reputation: 597234

They can be protected as well. Look at HttpServlet - all these methods are protected there. The entry-point to the servlet is the service(..) method - it is the only one that is potentially required to be public (but I don't know of such requirement - the container can invoke the service method with reflection)

Upvotes: 1

Related Questions