| Author |
Best way of intialization
|
tushar jayawant
Greenhorn
Joined: Aug 20, 2003
Posts: 19
|
|
Hi to all Which is best way of intialization the Instance Variable 1) class A { B b= new B(); C c = new C(); } 2) class A { B b ; C c ; A(){ b= new B(); c = new C(); } } Thankx in Advance Tushar
|
 |
Ernest Friedman-Hill
author and iconoclast
Marshal
Joined: Jul 08, 2003
Posts: 24059
|
|
If you initialize member variables in the body of the class, the compiler actually puts a copy of that initialization code at the beginning of each constructor, so in terms of efficiency or anything like that, they're really equivalent. The only thing that matters, then, is maintainability and readability. The rule I follow, loosely, is that primitive types can be initialized to constants in the class body, while objects are created in a constructor. The main reason for this is consistency; some objects have to be created in a constructor (or in an initializer block) because their constructors throw exceptions -- so to be consistent, I do them all that way. Other people may have other rules.
|
[Jess in Action][AskingGoodQuestions]
|
 |
tushar jayawant
Greenhorn
Joined: Aug 20, 2003
Posts: 19
|
|
Hi Thankx for the Reply...... Tushar
|
 |
Frank Harper
Greenhorn
Joined: May 27, 2004
Posts: 5
|
|
The advantage of initializing member variables in the body of the class is that you only have to do it once, instead of for each constructor. This eliminates potential bugs where someone forgets to initialize a member in in a certain constructor.
|
 |
 |
|
|
subject: Best way of intialization
|
|
|