Two interesting java questions

Q1. Can we write constructors in servlets ?

Ans. Container creates servlet instances using its no-argument constructor.  So the answer is, You can write constructor but, if you write a constructor with arguments, you need to provide a no-arg constructor also.

Q2. Why do we use init method to initialize a Servlet ? Why can’t we use constructor ?

Ans.  B’cose interfaces don’t allow to specify constructor signatures.  This is a bit high level answer. All servlets either directly or indirectly implements the GenericServlet interface.  In other words, you define the rules that a servlet should follow using the GenericServlet interface. But, how do you specify that a ServletConfig object should be passed as argument when creating a Servlet instance. You can’t declare a constructor rule in interface.
You can’t do this,

public interface GenericServlet {

public GenericServlet(ServletConfig sc) {

}

}
So the only way is to define a seperate init method. The name init is arbitrary, just a meaningful name.
public interface GenericServlet {

public init(ServletConfig sc) {

}

}

1 Comment »

  1. Rahul said

    Why java does not support the concept of pointers

RSS feed for comments on this post · TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.