May 24, 2010

FAQ's on Constructors

1. Is the Constructor mandatory for the class ?

Yes, It is mandatory to have the constructor in the class and that too should be accessible for the object i.e., it should have a proper access modifier. Say for example we have the private constructor in the class then it is of no use as it cannot be accessed by the object, so practically it is no available for the object. In such conditions it will raise an error.

2. What if I do not write the constructor ?

In such case the compiler will try to supply the no parameter constructor for your class behind the scene. Compiler will attempt this only if you do not write the constructor for the class. If you provide any constructor ( with or without parameters), then compiler will not make any such attempt.

3. What if I have the constructor public myDerivedClass() but not the public myBaseClass() ?

It will raise an error. If either the no parameter constructor is absent or it is in-accessible ( say it is private ), it will raise an error. You will have to take the precaution here.

4. Can we access static members from the non-static ( normal ) constructors ?

Yes, We can. There is no such restriction on non-static constructors. But there is one on static constructors that it can access only static members.

No comments:

Post a Comment