without - why do we need default constructor in java




How can a class have no constructor? (2)

A while back I asked about instantiating a HttpContext object. Now that I have learnt what I didn't know, what confuses me is that you cannot say HttpContext ctx = new HttpContext(); because the object does not have a constructor.

But doesn't every class need a constructor? In C#, if you don't provide one, the compiler automatically provides a default cstr for you.

Also, if I have a string (example: "Hello There!") and I say Convert.ToBoolean("Hello"), or any string, how does this work? What happens behind the scenes? I guess a book like CLR Via C# would be handy in this case.

What am I missing?


Constructor can be private or protected.
Also you can't create instance of abstract class, even if that class has public constructor.


HttpContext has a public constructor with two overloads but it's not the default (no params) one.

As an example, you need to pass in a SimpleWorkerRequest instance in order to instatiate an HttpContext instance and assign it to HttpContext.Current:

//Initialize this stuff with some crap
string appVirtualDir = "/"; 
string appPhysicalDir = @"C:\Documents and Settings\"; 
string page = @"localhost"; 
string query = string.Empty; 
TextWriter output = null;    
//Create a SimpleWorkerRequest object passing down the crap
SimpleWorkerRequest workerRequest = new SimpleWorkerRequest(appVirtualDir, appPhysicalDir, page, query, output);
//Create your fake HttpContext instance 
HttpContext.Current = new HttpContext(workerRequest);

See this link for details.

Anyway some classes don't have public constructors - think of a singleton class for example, constructor is private (and you can call the static getInstance method to get current instance or create it if it is null).

Cheers